<?php

/**
 * 73YC 购物流程函数库
 * ============================================================================
 * * 版权所有 2013-* 梅州络客网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.alork.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: 王海龙 $
 * $Id: index.php 17217 2014-08-28 10:36:08 王海龙 $
*/

if (!defined('IN_ECS'))
{
    die('Hacking attempt');
}

/**
 * 处理序列化的支付、配送的配置参数
 * 返回一个以name为索引的数组
 *
 * @access  public
 * @param   string       $cfg
 * @return  void
 */
function unserialize_config($cfg)
{
    if (is_string($cfg) && ($arr = unserialize($cfg)) !== false)
    {
        $config = array();

        foreach ($arr AS $key => $val)
        {
            $config[$val['name']] = $val['value'];
        }

        return $config;
    }
    else
    {
        return false;
    }
}
/**
 * 取得已安装的配送方式
 * @return  array   已安装的配送方式
 */
function shipping_list()
{
    $sql = 'SELECT shipping_id, shipping_name ' .
            'FROM ' . $GLOBALS['ecs']->table('shipping') .
            ' WHERE enabled = 1';

    return $GLOBALS['db']->getAll($sql);
}

/**
 * 取得配送方式信息
 * @param   int     $shipping_id    配送方式id
 * @return  array   配送方式信息
 */
function shipping_info($shipping_id)
{
    $sql = 'SELECT * FROM ' . $GLOBALS['ecs']->table('shipping') .
            " WHERE shipping_id = '$shipping_id' " .
            'AND enabled = 1';

    return $GLOBALS['db']->getRow($sql);
}

/**
 * 取得可用的配送方式列表
 * @param   array   $region_id_list     收货人地区id数组（包括国家、省、市、区）
 * @return  array   配送方式数组
 */
function available_shipping_list($region_id_list)
{
    $sql = 'SELECT s.shipping_id, s.shipping_code, s.shipping_name, ' .
                's.shipping_desc, s.insure, s.support_cod, a.configure ' .
            'FROM ' . $GLOBALS['ecs']->table('shipping') . ' AS s, ' .
                $GLOBALS['ecs']->table('shipping_area') . ' AS a, ' .
                $GLOBALS['ecs']->table('area_region') . ' AS r ' .
            'WHERE r.region_id ' . db_create_in($region_id_list) .
            ' AND r.shipping_area_id = a.shipping_area_id AND a.shipping_id = s.shipping_id AND s.enabled = 1 ORDER BY s.shipping_order';

    return $GLOBALS['db']->getAll($sql);
}

/**
 * 取得某配送方式对应于某收货地址的区域信息
 * @param   int     $shipping_id        配送方式id
 * @param   array   $region_id_list     收货人地区id数组
 * @return  array   配送区域信息（config 对应着反序列化的 configure）
 */
function shipping_area_info($shipping_id, $region_id_list)
{
    $sql = 'SELECT s.shipping_code, s.shipping_name, ' .
                's.shipping_desc, s.insure, s.support_cod, a.configure ' .
            'FROM ' . $GLOBALS['ecs']->table('shipping') . ' AS s, ' .
                $GLOBALS['ecs']->table('shipping_area') . ' AS a, ' .
                $GLOBALS['ecs']->table('area_region') . ' AS r ' .
            "WHERE s.shipping_id = '$shipping_id' " .
            'AND r.region_id ' . db_create_in($region_id_list) .
            ' AND r.shipping_area_id = a.shipping_area_id AND a.shipping_id = s.shipping_id AND s.enabled = 1';
    $row = $GLOBALS['db']->getRow($sql);

    if (!empty($row))
    {
        $shipping_config = unserialize_config($row['configure']);
        if (isset($shipping_config['pay_fee']))
        {
            if (strpos($shipping_config['pay_fee'], '%') !== false)
            {
                $row['pay_fee'] = floatval($shipping_config['pay_fee']) . '%';
            }
            else
            {
                 $row['pay_fee'] = floatval($shipping_config['pay_fee']);
            }
        }
        else
        {
            $row['pay_fee'] = 0.00;
        }
    }

    return $row;
}

/**
 * 计算运费
 * @param   float   $goods_amount       商品金额
 * @param   float   $pay_id             支付方式
 * @param   float   $shipping_count     是否有免邮商品
 * @param   float   $daodansong_id      是否属于导弹送
 * @param   float   $consignee          收货人信息
 * @param   float   $goods_weight       商品重量
 * @param   float   $user_id            用户ID
 * @return  float   运费
 */
function shipping_fee($goods_amount, $pay_id = '', $shipping_count='', $daodansong_id = 0, $consignee = array(), $goods_weight = 0, $user_id = 0)
{
    $user_id || $user_id = $_SESSION['user_id'];
    $shipping_fee = 10;
    $is_buy_shipping = array(2132,1982,1852,2294,2433,879,1006,860,1257,1119,1361,20,1484,2,1657,38);
    $rules = array(
        array(//贵州、四川、陕西：首重8、续重4.5(2727,2504,3067)
            'area'=>array(2727,2504,3067),
            'config'=>array(8,4.5),
        ),
        array(//云南、重庆：首重8、续重5(2830,2463)
            'area'=>array(2830,2463),
            'config'=>array(8,5),
        ),
        array(//新疆：首重16、续重16(3394)
            'area'=>array(3394),
            'config'=>array(16,16),
        ),
        array(//吉林、辽宁、黑龙江：首重8.5、续重5.8(628,499,706)
            'area'=>array(628,499,706),
            'config'=>array(8.5,5.8),
        ),
        array(//山西：首重8.5、续重5.5(233)
            'area'=>array(233),
            'config'=>array(8.5,5.5),
        ),
        array(//内蒙古、青海、甘肃、宁夏：首重12.3、续重9.3(375,3308,3195,3361)
            'area'=>array(375,3308,3195,3361),
            'config'=>array(12.3,9.3),
        ),
        array(//西藏：首重19、续重16(2984)
            'area'=>array(2984),
            'config'=>array(19,16),
        ),
    );
    if(in_array($consignee['province'],$is_buy_shipping)){
        // 限时包邮活动
        if( time() >= 1430409600 && time() <= 1433088000){
            // $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('order_info') . " WHERE order_status != 2 AND order_status != 3 AND user_id = $_SESSION[user_id]";
            // if(!$GLOBALS['db']->getOne($sql)){
            $shipping_fee = 0;
            // }
        }
        // 有免邮商品时包邮
        elseif($shipping_count){
            $shipping_fee = 0;
        }
        // 导蛋送地区超过20元免运费
        elseif($daodansong_id > 0){
            if($goods_amount >= 20){
                $shipping_fee = 0;
            }
        }
        // 超过128免运费
        elseif($goods_amount >= 128){
            $shipping_fee = 0;
        }
        // 支付运费
        else{
            $shipping_fee = 10;
        }
        // 参与全免计划的成员免邮
        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('user_freeplan') . " WHERE user_id = $user_id AND addtime < 1414230376";
        if($user_id&&$GLOBALS['db']->getOne($sql)){
            $shipping_fee = 0;
        }
    }else{
        foreach($rules AS $key => $rule){
            if(in_array($consignee['province'],$rule['area'])){
                $shipping_fee = $rule['config'][0];
                if($goods_weight > 1){
                    $goods_weight = ceil($goods_weight) - 1;
                    $shipping_fee += ($rule['config'][1] * $goods_weight);
                }
            }
        }
    }
    // 到付手续费
    if($pay_id == 3 && $goods_amount < 168){
        $shipping_fee += 5;
    }
    return $shipping_fee;
}

/**
 * 获取指定配送的保价费用
 *
 * @access  public
 * @param   string      $shipping_code  配送方式的code
 * @param   float       $goods_amount   保价金额
 * @param   mix         $insure         保价比例
 * @return  float
 */
function shipping_insure_fee($shipping_code, $goods_amount, $insure)
{
    if (strpos($insure, '%') === false)
    {
        /* 如果保价费用不是百分比则直接返回该数值 */
        return floatval($insure);
    }
    else
    {
        $path = ROOT_PATH . 'includes/modules/shipping/' . $shipping_code . '.php';

        if (file_exists($path))
        {
            include_once($path);

            $shipping = new $shipping_code;
            $insure   = floatval($insure) / 100;

            if (method_exists($shipping, 'calculate_insure'))
            {
                return $shipping->calculate_insure($goods_amount, $insure);
            }
            else
            {
                return ceil($goods_amount * $insure);
            }
        }
        else
        {
            return false;
        }
    }
}

/**
 * 取得已安装的支付方式列表
 * @return  array   已安装的配送方式列表
 */
function payment_list()
{
    $sql = 'SELECT pay_id, pay_name ' .
            'FROM ' . $GLOBALS['ecs']->table('payment') .
            ' WHERE enabled = 1';

    return $GLOBALS['db']->getAll($sql);
}

/**
 * 取得支付方式信息
 * @param   int     $pay_id     支付方式id
 * @return  array   支付方式信息
 */
function payment_info($pay_id)
{
    $sql = 'SELECT * FROM ' . $GLOBALS['ecs']->table('payment') .
            " WHERE pay_id = '$pay_id' AND enabled = 1";

    return $GLOBALS['db']->getRow($sql);
}

/**
 * 获得订单需要支付的支付费用
 *
 * @access  public
 * @param   integer $payment_id
 * @param   float   $order_amount
 * @param   mix     $cod_fee
 * @return  float
 */
function pay_fee($payment_id, $order_amount, $cod_fee=null)
{
    $pay_fee = 0;
    $payment = payment_info($payment_id);
    $rate    = ($payment['is_cod'] && !is_null($cod_fee)) ? $cod_fee : $payment['pay_fee'];
    if (strpos($rate, '%') !== false)
    {
        /* 支付费用是一个比例 */
        $val     = floatval($rate) / 100;
        $pay_fee = $val > 0 ? $order_amount * $val /(1- $val) : 0;
    }
    else
    {
        $pay_fee = floatval($rate);
    }

    return round($pay_fee, 2);
}

/**
 * 取得可用的支付方式列表
 * @param   bool    $support_cod        配送方式是否支持货到付款
 * @param   int     $cod_fee            货到付款手续费（当配送方式支持货到付款时才传此参数）
 * @param   int     $is_online          是否支持在线支付
 * @return  array   配送方式数组
 */
function available_payment_list($support_cod, $cod_fee = 0, $is_online = false)
{
    $sql = 'SELECT pay_id, pay_code, pay_name, pay_fee, pay_desc, pay_config, is_cod' .
            ' FROM ' . $GLOBALS['ecs']->table('payment') .
            ' WHERE enabled = 1 ';
    if (!$support_cod)
    {
        $sql .= 'AND is_cod = 0 '; // 如果不支持货到付款
    }
    if ($is_online)
    {
        $sql .= "AND is_online = '1' ";
    }
    $sql .= 'ORDER BY pay_order'; // 排序
    $res = $GLOBALS['db']->query($sql);

    $pay_list = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        if ($row['is_cod'] == '1')
        {
            $row['pay_fee'] = $cod_fee;
        }

        $row['format_pay_fee'] = strpos($row['pay_fee'], '%') !== false ? $row['pay_fee'] :
        price_format($row['pay_fee'], false);
        $modules[] = $row;
    }

    include_once(ROOT_PATH.'includes/lib_compositor.php');

    if(isset($modules))
    {
        return $modules;
    }
}

/**
 * 取得包装列表
 * @return  array   包装列表
 */
function pack_list()
{
    $sql = 'SELECT * FROM ' . $GLOBALS['ecs']->table('pack');
    $res = $GLOBALS['db']->query($sql);

    $list = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $row['format_pack_fee'] = price_format($row['pack_fee'], false);
        $row['format_free_money'] = price_format($row['free_money'], false);
        $list[] = $row;
    }

    return $list;
}

/**
 * 取得包装信息
 * @param   int     $pack_id    包装id
 * @return  array   包装信息
 */
function pack_info($pack_id)
{
    $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('pack') .
            " WHERE pack_id = '$pack_id'";

    return $GLOBALS['db']->getRow($sql);
}

/**
 * 根据订单中的商品总额来获得包装的费用
 *
 * @access  public
 * @param   integer $pack_id
 * @param   float   $goods_amount
 * @return  float
 */
function pack_fee($pack_id, $goods_amount)
{
    $pack = pack_info($pack_id);

    $val = (floatval($pack['free_money']) <= $goods_amount && $pack['free_money'] > 0) ? 0 : floatval($pack['pack_fee']);

    return $val;
}

/**
 * 取得贺卡列表
 * @return  array   贺卡列表
 */
function card_list()
{
    $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('card');
    $res = $GLOBALS['db']->query($sql);

    $list = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $row['format_card_fee'] = price_format($row['card_fee'], false);
        $row['format_free_money'] = price_format($row['free_money'], false);
        $list[] = $row;
    }

    return $list;
}

/**
 * 取得贺卡信息
 * @param   int     $card_id    贺卡id
 * @return  array   贺卡信息
 */
function card_info($card_id)
{
    $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('card') .
            " WHERE card_id = '$card_id'";

    return $GLOBALS['db']->getRow($sql);
}

/**
 * 根据订单中商品总额获得需要支付的贺卡费用
 *
 * @access  public
 * @param   integer $card_id
 * @param   float   $goods_amount
 * @return  float
 */
function card_fee($card_id, $goods_amount)
{
    $card = card_info($card_id);

    return ($card['free_money'] <= $goods_amount && $card['free_money'] > 0) ? 0 : $card['card_fee'];
}

/**
 * 取得订单信息
 * @param   int     $order_id   订单id（如果order_id > 0 就按id查，否则按sn查）
 * @param   string  $order_sn   订单号
 * @return  array   订单信息（金额都有相应格式化的字段，前缀是formated_）
 */
function order_info($order_id, $order_sn = '')
{
    /* 计算订单各种费用之和的语句 */
    $total_fee = " (goods_amount - discount + tax + shipping_fee + insure_fee + pay_fee ) AS total_fee ";
    $order_id = intval($order_id);
    if ($order_id > 0)
    {
        $sql = "SELECT *, " . $total_fee . " FROM " . $GLOBALS['ecs']->table('order_info') .
                " oi LEFT JOIN " . $GLOBALS['ecs']->table('daodansong_area') . " da ON da.area_id = oi.daodansong_id WHERE order_id = '$order_id'";

    }
    else
    {
        $sql = "SELECT *, " . $total_fee . "  FROM " . $GLOBALS['ecs']->table('order_info') .
                " oi LEFT JOIN " . $GLOBALS['ecs']->table('daodansong_area') . " da ON da.area_id = oi.daodansong_id WHERE order_sn = '$order_sn'";
    }
    $order = $GLOBALS['db']->getRow($sql);

    /* 格式化金额字段 */
    if ($order)
    {
        $order['order_amounts']           = $order['order_amount'];
        $order['formated_goods_amount']   = price_format($order['goods_amount'], false);
        $order['formated_discount']       = price_format($order['discount'], false);
        $order['formated_tax']            = price_format($order['tax'], false);
        $order['formated_shipping_fee']   = price_format($order['shipping_fee'], false);
        $order['formated_insure_fee']     = price_format($order['insure_fee'], false);
        $order['formated_pay_fee']        = price_format($order['pay_fee'], false);
        $order['formated_total_fee']      = price_format($order['total_fee'], false);
        $order['formated_money_paid']     = price_format($order['money_paid'], false);
        $order['formated_bonus']          = price_format($order['bonus'], false);
        $order['formated_integral_money'] = price_format($order['integral_money'], false);
        $order['formated_surplus']        = price_format($order['surplus'], false);
        $order['formated_order_amount']   = price_format(abs($order['order_amount']), false);
        $order['formated_add_time']       = local_date($GLOBALS['_CFG']['time_format'], $order['add_time']);


        $order['formated_goods_amounts']   = price_format($order['goods_amount'], false);
        $order['formated_discounts']       = price_format($order['discount'], false);
        $order['formated_taxs']            = price_format($order['tax'], false);
        $order['formated_shipping_fees']   = price_format($order['shipping_fee'], false);
        $order['formated_insure_fees']     = price_format($order['insure_fee'], false);
        $order['formated_pay_fees']        = price_format($order['pay_fee'], false);
        $order['formated_total_fees']      = price_format($order['total_fee'], false);
        $order['formated_money_paids']     = price_format($order['money_paid'], false);
        $order['formated_bonuss']          = price_format($order['bonus'], false);
        $order['formated_integral_moneys'] = price_format($order['integral_money'], false);
        $order['formated_surpluss']        = price_format($order['surplus'], false);
        $order['formated_order_amounts']   = price_format(abs($order['order_amount']), false);
    }

    return $order;
}


/**
 * 判断订单是否已完成
 * @param   array   $order  订单信息
 * @return  bool
 */
function order_finished($order)
{
    return $order['order_status']  == OS_CONFIRMED &&
        ($order['shipping_status'] == SS_SHIPPED || $order['shipping_status'] == SS_RECEIVED) &&
        ($order['pay_status']      == PS_PAYED   || $order['pay_status'] == PS_PAYING);
}

/**
 * 取得订单商品
 * @param   int     $order_id   订单id
 * @return  array   订单商品数组
 */
function order_goods($order_id)
{
    $count="";
    $sql = "SELECT o.rec_id, o.goods_id,o.is_sale, o.goods_name, o.goods_sku, o.market_price, o.goods_number, g.goods_thumb, g.goods_img, " .
            "o.goods_price, o.goods_attr, o.is_real, o.parent_id, o.is_gift, g.give_integral, " .
            "o.goods_price * o.goods_number AS subtotal, o.extension_code, o.goods_attr_sku " .
            "FROM " . $GLOBALS['ecs']->table('order_goods') . " o ".
            "LEFT JOIN " . $GLOBALS['ecs']->table('goods') . " g ON g.goods_id = o.goods_id " .
            " WHERE o.order_id = '$order_id'";

    $res = $GLOBALS['db']->query($sql);

    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        if ($row['extension_code'] == 'package_buy')
        {
            $row['package_goods_list'] = get_package_goods($row['goods_id']);
            $goods_list[] = $row;
        }
        if(($row['extension_code'] == 'libao'||$row['extension_code'] == 'gift') && $row['goods_id'] == 0){
            $sql = "SELECT img FROM " . $GLOBALS['ecs']->table('activity') . " WHERE parent_id = $row[parent_id]";
            $row['goods_thumb'] = $GLOBALS['db']->getOne($sql);
            $count=$row["goods_number"]+$count;
            $goods_list[] = $row;
        }elseif($row['extension_code'] != 'libao'){
            $count=$row["goods_number"]+$count;
            $goods_list[] = $row;
        }

    }

    $goods_list[0]['count']= $count;
    return $goods_list;
}

/**
 * 取得订单总金额
 * @param   int     $order_id   订单id
 * @param   bool    $include_gift   是否包括赠品
 * @return  float   订单总金额
 */
function order_amount($order_id, $include_gift = true)
{
    $sql = "SELECT SUM(goods_price * goods_number) " .
            "FROM " . $GLOBALS['ecs']->table('order_goods') .
            " WHERE order_id = '$order_id' AND (parent_id = 0 OR (parent_id > 0 AND goods_id = 0 AND extension_code = 'libao'))";
    if (!$include_gift)
    {
        $sql .= " AND is_gift = 0";
    }

    return floatval($GLOBALS['db']->getOne($sql));
}

/**
 * 取得某订单商品总重量和总金额（对应 cart_weight_price）
 * @param   int     $order_id   订单id
 * @return  array   ('weight' => **, 'amount' => **, 'formated_weight' => **)
 */
function order_weight_price($order_id)
{
    $sql = "SELECT SUM(g.goods_weight * o.goods_number) AS weight, " .
                "SUM(o.goods_price * o.goods_number) AS amount ," .
                "SUM(o.goods_number) AS number " .
            "FROM " . $GLOBALS['ecs']->table('order_goods') . " AS o, " .
                $GLOBALS['ecs']->table('goods') . " AS g " .
            "WHERE o.order_id = '$order_id' " .
            "AND o.goods_id = g.goods_id";

    $row = $GLOBALS['db']->getRow($sql);
    $row['weight'] = floatval($row['weight']);
    $row['amount'] = floatval($row['amount']);
    $row['number'] = intval($row['number']);

    /* 格式化重量 */
    $row['formated_weight'] = formated_weight($row['weight']);

    return $row;
}

/**
 * 获得订单中的费用信息（直接购买）
 *
 * @access  public
 * @param   array   $order
 * @param   array   $goods
 * @param   array   $consignee
 * @param   bool    $is_gb_deposit  是否团购保证金（如果是，应付款金额只计算商品总额和支付费用，可以获得的积分取 $gift_integral）
 * @return  array
 */
function order_fee2($order, $goods, $consignee)
{
    /* 初始化订单的扩展code */
    if (!isset($order['extension_code']))
    {
        $order['extension_code'] = '';
    }

    $total  = array('real_goods_count' => 0,//商品数量
                    'goods_price'      => 0,//商品总价
                    'goods_price_formated'=>0,
                    'market_price'     => 0,//商品总市场价
                    'market_price_formated'=>0,
                    'shipping_fee'     => 0,//配送费用
                    'shipping_fee_formated'=>0,
                    'integral_money'   => 0,//积分抵消费用
                    'bonus'            => 0,//红包抵消费用
                    'bonus_formated'   => 0,
                    'pay_fee'          => 0,//已经支付金额
                    'goods_weight'     => 0,
                    );
    $weight = 0;

    /* 商品总价 */
    foreach ($goods AS $val)
    {
        /* 统计实体商品的个数 */
        if ($val['is_real'])
        {
            $total['real_goods_count']++;
        }
        if($val['is_gift'] == 0){
            $total['goods_weight'] += $val['goods_weight'] * $val['goods_number'];
        }
        /* 过滤礼包商品价格计算 */
        if($val['extension_code'] == 'libao' && $val['goods_id'] > 0){
            continue;
        }
        // 促销？
        // if ($val['promote_price'] > 0)
        // {
        //     $total['goods_price']  += $val['promote_price'] * $val['goods_number'];//商品总售价
        // }else
        // {
        //     $total['goods_price']  += $val['goods_price'] * $val['goods_number'];//商品总售价
        // }
        $total['goods_price']  += $val['goods_price'] * $val['goods_number'];       //商品总售价
        $total['market_price'] += $val['market_price'] * $val['goods_buy_num'];     //商品总市场价
    }
    $total['goods_price_formated']  = price_format($total['goods_price'], false);
    $total['market_price_formated'] = price_format($total['market_price'], false);
    ($total['market_price']-$total['goods_price']>0) ? $total['preferential_price']=$total['market_price']-$total['goods_price'] : $total['preferential_price']=0;

    /* 配送费用 */
    // 查看商品是否免邮
    $sql = 'SELECT count(*) FROM ' . $GLOBALS['ecs']->table('goods') . " WHERE  `goods_id` = '" .
           $goods[0]['goods_id'] . "' AND (`extension_code` = 'package_buy' OR `is_shipping` = 1)";
    $shipping_count = $GLOBALS['db']->getOne($sql);

    $total['shipping_fee'] = shipping_fee($total['goods_price'], $order['pay_id'], $shipping_count, $order['daodansong_id'], $consignee, $total['goods_weight']);

    $total['shipping_fee_formated']   = price_format($total['shipping_fee'], false);

    /* 保存订单信息 */
    $_SESSION['flow_order'] = $order;
    $se_flow_type = isset($_SESSION['flow_type']) ? $_SESSION['flow_type'] : '';
    /* 支付费用 */
    $total['amount'] = $total['goods_price'] + $total['shipping_fee'];
    $total['amount_formated']  = price_format($total['amount'], false);

    /* 取得可以得到的积分和红包 */
    $total['will_get_integral'] = get_give_integral($goods);

    return $total;
}

/**
 * 获得订单中的费用信息（购物车结算）
 *
 * @access  public
 * @param   array   $order
 * @param   array   $goods
 * @param   array   $consignee
 * @param   bool    $is_gb_deposit  是否团购保证金（如果是，应付款金额只计算商品总额和支付费用，可以获得的积分取 $gift_integral）
 * @return  array
 */
function order_fee($order, $goods, $consignee)
{



    /* 初始化订单的扩展code */
    if (!isset($order['extension_code']))
    {
        $order['extension_code'] = '';
    }

    $total  = array('real_goods_count' => 0,//商品数量
                    'goods_price'      => 0,//商品总价
                    'goods_price_formated'=>0,
                    'market_price'     => 0,//商品总市场价
                    'market_price_formated'=>0,
                    'shipping_fee'     => 0,//配送费用
                    'shipping_fee_formated'=>0,
                    'integral_money'   => 0,//积分抵消费用
                    'bonus'            => 0,//红包抵消费用
                    'bonus_formated'   => 0,
                    'pay_fee'          => 0,//已经支付金额
                    'goods_weight'     => 0,
                    );
    $weight = 0;

    /* 商品总价 */
    foreach ($goods AS $val)
    {
        /* 统计实体商品的个数 */
        if ($val['is_real'])
        {
            $total['real_goods_count']++;
        }
        if($val['is_gift'] == 0){
            $total['goods_weight'] += $val['goods_weight'] * $val['goods_number'];
        }
        /* 过滤礼包商品价格计算 */
        if($val['extension_code'] == 'libao' && $val['parent_id'] > 0 && $val['goods_id'] > 0){
            continue;
        }
        // 促销？
        // if ($val['promote_price'] > 0)
        // {
        //     $total['goods_price']  += $val['promote_price'] * $val['goods_buy_num'];//商品总售价
        // }else
        // {
        //     $total['goods_price']  += $val['goods_buy_price'] * $val['goods_buy_num'];//商品总售价
        // }
        $total['goods_price']  += $val['goods_price'] * $val['goods_number'];  //商品总售价
        $total['market_price'] += $val['market_price'] * $val['goods_number'];     //商品总市场价
    }





    $total['goods_price_formated']  = price_format($total['goods_price'], false);
    $total['market_price_formated'] = price_format($total['market_price'], false);
    ($total['market_price']-$total['goods_price']>0) ? $total['preferential_price']=$total['market_price']-$total['goods_price'] : $total['preferential_price']=0;
    /* 配送费用 */

    // 查看购物车中是否存在免运费商品，若是则把运费赋为零
    $sql = 'SELECT count(*) FROM ' . $GLOBALS['ecs']->table('cart') . " WHERE  `session_id` = '" . SESS_ID. "' AND (`extension_code` = 'package_buy' OR `is_shipping` = 1)";
    $shipping_count = $GLOBALS['db']->getOne($sql);
    $total['shipping_fee'] = shipping_fee($total['goods_price'], $order['pay_id'], $shipping_count, $order['daodansong_id'], $consignee, $total['goods_weight']);

    $total['shipping_fee_formated']   = price_format($total['shipping_fee'], false);

    /* 保存订单信息 */
    $_SESSION['flow_order'] = $order;
    $se_flow_type = isset($_SESSION['flow_type']) ? $_SESSION['flow_type'] : '';
    /* 支付费用 */
    $total['amount'] = $total['goods_price'] + $total['shipping_fee'];
    $total['amount_formated']  = price_format($total['amount'], false);

    /* 取得可以得到的积分和红包 */
    $total['will_get_integral'] = get_give_integral($goods);

    return $total;
}

/**
 * 修改订单
 * @param   int     $order_id   订单id
 * @param   array   $order      key => value
 * @return  bool
 */
function update_order($order_id, $order)
{
    return $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('order_info'),
        $order, 'UPDATE', "order_id = '$order_id'");
}

/**
 * 修改合单
 * @param   int     $order_id   订单id
 * @param   array   $order      key => value
 * @return  bool
 */
function update_order_join($order_sn, $order)
{
    return $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('order_info'),
        $order, 'UPDATE', "join_id = '$order_sn'");
}


/**
 * 得到新订单号
 * @return  string
 */
function get_order_sn()
{
    /* 选择一个随机的方案 */
    mt_srand((double) microtime() * 1000000);

    return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}

/**
 * 取得购物车商品
 * @param   int     $type   类型：默认普通商品
 * @return  array   购物车商品数组
 */
function cart_goods()
{
    $user_id = $_SESSION['user_id']?$_SESSION['user_id']:0;

    $sql =  " SELECT g.goods_id,g.goods_thumb, g.goods_weight, g.preferential_price ,g.seller_note,g.promote_start_date, g.promote_price, g.promote_end_date,".
            " c.rec_id, c.user_id, c.goods_id, c.goods_name, c.goods_sku,c.goods_attr_id, c.goods_attr_sku, c.goods_number,c.area_id, " .
            " c.market_price, c.goods_price, c.goods_attr, c.is_real, c.extension_code, c.parent_id, c.is_gift, c.is_shipping, c.compose_note, " .
            " c.goods_price * c.goods_number AS subtotal " .
            " FROM " . $GLOBALS['ecs']->table('cart') .
            " c LEFT JOIN " . $GLOBALS['ecs']->table('goods') . " g ON(g.goods_id = c.goods_id) ".
            " WHERE (session_id = '" . SESS_ID . "'" . ($user_id?" OR user_id = $user_id":'')  . ")" ;

    $arr = $GLOBALS['db']->getAll($sql);

    /* 格式化价格及礼包商品 */
    foreach ($arr as $key => $value)
    {
        /*判断商品是否为闪购商品*/
        if($value['promote_start_date']<time()&&time()<$value['promote_end_date']||$value['extension_code']=='limit'){
            $arr[$key]['is_buy']=(limit_num($value['goods_id'],2)<$value['goods_number'])?0:1;
            $arr[$key]['goods_stock']=limit_num($value['goods_id'],2);
        }
        //过时不能购买
        if($value['extension_code']=='limit'&&time()>$value['promote_end_date']){
            $arr[$key]['is_buy'] = 0;
        }
        //过滤礼包商品
        if($value['extension_code'] == 'libao'&&$value['goods_id']!=0){
               unset($arr[$key]);
        }
        if($value['extension_code'] == 'libao' && $value['goods_id'] == 0){
            $sql = "SELECT img FROM " . $GLOBALS['ecs']->table('activity') . " WHERE parent_id = $value[parent_id]";
            $arr[$key]['goods_thumb'] = $GLOBALS['db']->getOne($sql);
            $arr[$key]['is_buy'] = 1;
        }
        /*普通商品查询库存*/
        if (empty($value['extension_code'])) {
            /*颜料商品库存*/
            if (!empty($value['goods_attr_sku'])) {
                $arr[$key]['goods_stock'] = $GLOBALS['virtualStock']->selectStock($value['goods_attr_sku']);
                $arr[$key]['is_buy']      = $arr[$key]['goods_stock']<$arr[$key]['goods_number']?0:1;
            }
            else{
                $stock                    = $GLOBALS['virtualStock']->selectStock($value['goods_sku']);
                $arr[$key]['goods_stock'] = $GLOBALS['virtualStock']->selectStock($value['goods_sku']);
                $arr[$key]['is_buy']      = $arr[$key]['goods_stock']<$arr[$key]['goods_number']?0:1;
            }
        }
    }

    return $arr;
}


/**
 * 取得购物车选中商品
 * @param   int     $type   类型：默认普通商品
 * @return  array   购物车商品数组
 * @author  Jo 
 */
function cart_goods_checkbox($rec_id,$type = CART_GENERAL_GOODS,$area_id = 0)
{

    if (empty($rec_id)) {
        header('location: flow.php');exit;
    }
    $user_id = $_SESSION['user_id'] ? $_SESSION['user_id'] : 0;

    $sql = "SELECT c.rec_id, g.goods_id,g.goods_thumb, g.goods_weight, g.preferential_price ,g.seller_note,g.promote_start_date, g.promote_price, g.promote_end_date, c.user_id, c.goods_id, c.goods_name, c.goods_sku,c.goods_attr_id, c.goods_attr_sku, c.goods_number,c.area_id, " .
            "c.market_price, c.goods_price, c.goods_attr, c.is_real, c.extension_code, c.parent_id, c.is_gift, c.is_shipping, c.compose_note, " .
            "c.goods_price * c.goods_number AS subtotal " .
            "FROM " . $GLOBALS['ecs']->table('cart') .
            " c LEFT JOIN " . $GLOBALS['ecs']->table('goods') . " g ON(g.goods_id = c.goods_id) ".
            // " LEFT JOIN " . $GLOBALS['ecs']->table('goods_stock') . " gs ON(gs.goods_id = c.goods_id AND gs.goods_attr_id = c.goods_attr_id AND gs.area_id = 3) ".
            " WHERE (session_id = '" . SESS_ID . "'" . ($user_id?" OR user_id = $user_id":'')  . ")" .
            " AND rec_type = '$type' AND c.rec_id IN ($rec_id)";

    $arr = $GLOBALS['db']->getAll($sql);

    /* 格式化价格及礼包商品 */
    foreach ($arr as $key => $value)
    {
        $recList[] = $value['rec_id'];
        if($value['promote_start_date']<time()&&time()<$value['promote_end_date']||$value['extension_code']=='limit'){
            $arr[$key]['is_buy']=(limit_num($value['goods_id'],2)<$value['goods_number'])?0:1;
            $arr[$key]['goods_stock']=limit_num($value['goods_id'],2);
        }
        //过时不能购买
        if($value['extension_code']=='limit'&&time()>$value['promote_end_date']){
            $arr[$key]['is_buy'] = 0;
        }
        //过滤礼包商品
        if($value['extension_code'] == 'libao'){
            $arr[$key]['is_buy'] = 1;
        }
        if($value['extension_code'] == 'libao' && $value['goods_id'] == 0){
            $sql = "SELECT img FROM " . $GLOBALS['ecs']->table('activity') . " WHERE parent_id = $value[parent_id]";
            $arr[$key]['goods_thumb'] = $GLOBALS['db']->getOne($sql);
        }


        /*普通商品查询库存*/
        if (empty($value['extension_code'])) {
            /*颜料商品库存*/
            if (!empty($value['goods_attr_sku'])) {
                $arr[$key]['goods_stock'] = $GLOBALS['virtualStock']->selectStock($value['goods_attr_sku']);
                $arr[$key]['is_buy']      = $arr[$key]['goods_stock']<$arr[$key]['goods_number']?0:1;
            }
            else{
                $arr[$key]['goods_stock'] = $GLOBALS['virtualStock']->selectStock($value['goods_sku']);
                $arr[$key]['is_buy']      = $arr[$key]['goods_stock']<$arr[$key]['goods_number']?0:1;
            }
        }
        $arr[$key]['formated_market_price']                       = price_format($value['market_price'], false);
        $arr[$key]['formated_goods_price']                        = price_format($value['goods_price'], false);
        $arr[$key]['formated_subtotal']                           = price_format($value['subtotal'], false);
        // $arr[$key]['preferential']                                = $value['market_price']-$value['goods_price'];
        // $arr[$key]['preferential']>0 ? $arr[$key]['preferential'] = $arr[$key]['preferential']*$arr[$key]['goods_number'] : $arr[$key]['preferential']=0;
    }
    // 检查是否所有商品均存在，不存在刚返回false
    foreach (explode($rec_id) as $key => $value) {
        if (!in_array($value, $recList)) {
            return false;
        }
    }
// dump($arr);
    return $arr;
}

/**
 * 取得购物车总金额
 * @params  boolean $include_gift   是否包括赠品
 * @param   int     $type           类型：默认普通商品
 * @return  float   购物车总金额
 */
function cart_amount($include_gift = true, $type = CART_GENERAL_GOODS)
{
    $sql = "SELECT SUM(goods_price * goods_number) " .
            " FROM " . $GLOBALS['ecs']->table('cart') .
            " WHERE session_id = '" . SESS_ID . "' " .
            "AND rec_type = '$type' ";

    if (!$include_gift)
    {
        $sql .= ' AND is_gift = 0 AND goods_id > 0';
    }

    return floatval($GLOBALS['db']->getOne($sql));
}

/**
 * 检查某商品是否已经存在于购物车
 *
 * @access  public
 * @param   integer     $id
 * @param   array       $spec
 * @param   int         $type   类型：默认普通商品
 * @return  boolean
 */
function cart_goods_exists($id, $spec, $type = CART_GENERAL_GOODS)
{
    /* 检查该商品是否已经存在在购物车中 */
    $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('cart').
            "WHERE session_id = '" .SESS_ID. "' AND goods_id = '$id' ".
            "AND parent_id = 0 AND goods_attr = '" .get_goods_attr_info($spec). "' " .
            "AND rec_type = '$type'";

    return ($GLOBALS['db']->getOne($sql) > 0);
}

/**
 * 获得购物车中商品的总重量、总价格、总数量
 *
 * @access  public
 * @param   int     $type   类型：默认普通商品
 * @return  array
 */
function cart_weight_price($type = CART_GENERAL_GOODS)
{
    $package_row['weight'] = 0;
    $package_row['amount'] = 0;
    $package_row['number'] = 0;

    $packages_row['free_shipping'] = 1;

    /* 计算超值礼包内商品的相关配送参数 */
    $sql = 'SELECT goods_id, goods_number, goods_price FROM ' . $GLOBALS['ecs']->table('cart') . " WHERE extension_code = 'package_buy' AND session_id = '" . SESS_ID . "'";
    $row = $GLOBALS['db']->getAll($sql);

    if ($row)
    {
        $packages_row['free_shipping'] = 0;
        $free_shipping_count = 0;

        foreach ($row as $val)
        {
            // 如果商品全为免运费商品，设置一个标识变量
            $sql = 'SELECT count(*) FROM ' .
                    $GLOBALS['ecs']->table('package_goods') . ' AS pg, ' .
                    $GLOBALS['ecs']->table('goods') . ' AS g ' .
                    "WHERE g.goods_id = pg.goods_id AND g.is_shipping = 0 AND pg.package_id = '"  . $val['goods_id'] . "'";
            $shipping_count = $GLOBALS['db']->getOne($sql);

            if ($shipping_count > 0)
            {
                // 循环计算每个超值礼包商品的重量和数量，注意一个礼包中可能包换若干个同一商品
                $sql = 'SELECT SUM(g.goods_weight * pg.goods_number) AS weight, ' .
                    'SUM(pg.goods_number) AS number FROM ' .
                    $GLOBALS['ecs']->table('package_goods') . ' AS pg, ' .
                    $GLOBALS['ecs']->table('goods') . ' AS g ' .
                    "WHERE g.goods_id = pg.goods_id AND g.is_shipping = 0 AND pg.package_id = '"  . $val['goods_id'] . "'";

                $goods_row = $GLOBALS['db']->getRow($sql);
                $package_row['weight'] += floatval($goods_row['weight']) * $val['goods_number'];
                $package_row['amount'] += floatval($val['goods_price']) * $val['goods_number'];
                $package_row['number'] += intval($goods_row['number']) * $val['goods_number'];
            }
            else
            {
                $free_shipping_count++;
            }
        }

        $packages_row['free_shipping'] = $free_shipping_count == count($row) ? 1 : 0;
    }

    /* 获得购物车中非超值礼包商品的总重量 */
    $sql    = 'SELECT SUM(g.goods_weight * c.goods_number) AS weight, ' .
                    'SUM(c.goods_price * c.goods_number) AS amount, ' .
                    'SUM(c.goods_number) AS number '.
                'FROM ' . $GLOBALS['ecs']->table('cart') . ' AS c '.
                'LEFT JOIN ' . $GLOBALS['ecs']->table('goods') . ' AS g ON g.goods_id = c.goods_id '.
                "WHERE c.session_id = '" . SESS_ID . "' " .
                "AND rec_type = '$type' AND g.is_shipping = 0 AND c.extension_code != 'package_buy'";
    $row = $GLOBALS['db']->getRow($sql);

    $packages_row['weight'] = floatval($row['weight']) + $package_row['weight'];
    $packages_row['amount'] = floatval($row['amount']) + $package_row['amount'];
    $packages_row['number'] = intval($row['number']) + $package_row['number'];
    /* 格式化重量 */
    $packages_row['formated_weight'] = formated_weight($packages_row['weight']);

    return $packages_row;
}

/**
 * 得到直接购买的商品信息
 *
 */
function get_goods_msg($goods_id, $num = 1, $spec = array(), $parent = 0, $attr='')
{
    $GLOBALS['err']->clean();

    /* 取得商品信息 */
    $sql = "SELECT g.goods_id, g.goods_name, g.goods_weight, g.seller_note, g.goods_sku, g.compose_note, g.is_on_sale,g.seller_note,".
            "g.market_price, g.promote_price, g.promote_start_date, g.cat_id, g.goods_thumb, ".
            "g.promote_end_date, g.goods_weight, g.integral, g.extension_code, ".
            " g.is_alone_sale, g.is_shipping, gs.goods_number AS goods_stock, g.shop_price, g.preferential_price ".
            " FROM " .$GLOBALS['ecs']->table('goods'). " AS g ".
            " LEFT JOIN " .$GLOBALS['ecs']->table('goods_stock'). " AS gs ON gs.goods_id = g.goods_id AND gs.area_id = '$_SESSION[area_id]' AND " . ($spec?('gs.goods_attr_id = ' . $spec[0]):'gs.goods_attr_id = 0') .
            " WHERE g.goods_id = '$goods_id'" .
            " AND g.is_delete = 0";
    $goods_msg = $GLOBALS['db']->getRow($sql);

    $goods_msg['goods_number'] = $num;       // 购买商品的数量

    // 判断商品库存是否足够
    if( $goods_msg['goods_stock'] >= $goods_msg['goods_number']){
        $goods_msg['is_buy'] = 1;
    }else{
        $goods_msg['is_buy'] = 0;
    }

    // 判断购买商品的数量是否大于优惠数量
    if( $goods_msg['goods_number'] >= 3){
        $goods_msg['goods_price'] = $goods_msg['preferential_price'];
    }else{
        $goods_msg['goods_price'] = $goods_msg['shop_price'];
    }
    $goods_msg['subtotal'] = $goods_msg['goods_number'] * $goods_msg['goods_price'];   //总价

    $goods_msg['formated_subtotal']     = price_format($goods_msg['subtotal'],false);
    $goods_msg['formated_market_price'] = price_format($goods_msg['market_price'], false);
    $goods_msg['formated_goods_price']  = price_format($goods_msg['shop_price'], false);

    //判断是否在促销中
    if($goods_msg['promote_start_date']<time() && $goods_msg['promote_end_date']>time()){
        $goods_msg['goods_number'] = limit_num($goods_id,2);        //闪购库存
        $goods_msg['extension_code']    = "limit";
        $add_time = time();
    }

    if (empty($goods_msg))
    {
        $GLOBALS['err']->add($GLOBALS['_LANG']['goods_not_exists'], ERR_NOT_EXISTS);

        return false;
    }

    /* 是否正在销售 */
    if ($goods_msg['is_on_sale'] == 0)
    {
        $GLOBALS['err']->add($GLOBALS['_LANG']['not_on_sale'], ERR_NOT_ON_SALE);

        return false;
    }

    /* 不是配件时检查是否允许单独销售 */
    if ($goods_msg['is_alone_sale'] == 0)
    {
        $GLOBALS['err']->add($GLOBALS['_LANG']['cannt_alone_sale'], ERR_CANNT_ALONE_SALE);

        return false;
    }
    //检查：商品购买数量是否大于总库存
    if (!$spec && $num > $goods_msg['goods_stock'])
    {
        $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['shortage'], $goods_msg['goods_number']), ERR_OUT_OF_STOCK);
        return false;
    }
     /* 扩展属性格式化 */
    if($spec){
        $goods_attr_id          = join(',', $spec);
        $goods_attr             = get_goods_attr_info($spec);
        $goods_attr_sku         = get_goods_attr_sku($spec);
    }else{
        $goods_attr_id          = 0;
        $goods_attr             = '';
        $goods_attr_sku         = '';
    }
    $goods_msg['goods_attr_id'] = $goods_attr_id;
    $goods_msg['goods_attr']    = $goods_attr;
    $goods_msg['goods_attr_sku']= $goods_attr_sku;

    $goods_msg['is_gift']   = 0;
    $goods_msg['is_real']   = 1;
    $goods_msg['area_id']   = $_SESSION['area_id'];

    $goods_msg['product_id'] = isset($product_info['product_id']) ? $product_info['product_id'] : 0;

    /* 判断是否是礼包 */
    if( $goods_msg['extension_code'] == 'libao' ){
        $goods_msg['parent_id'] = 1;
    }else{
        $goods_msg['parent_id'] = 0;
    }

    $goods_msg['is_imme_checkout'] = 1;

    return $goods_msg;
}

/**
 * 添加商品到购物车
 *
 * @access  public
 * @param   integer $goods_id   商品编号
 * @param   integer $num        商品数量
 * @param   array   $spec       规格值对应的id数组
 * @param   integer $parent     基本件
 * @return  boolean
 */
function addto_cart($goods_id, $num = 1, $spec = array(), $parent = 0, $attr='')
{
    $GLOBALS['err']->clean();

    /* 取得商品信息 */
    $sql = "SELECT g.goods_name, g.goods_sku, g.compose_note, g.is_on_sale,g.seller_note,".
            "g.market_price, g.promote_price, g.promote_start_date, g.cat_id, ".
            "g.promote_end_date, g.goods_weight, g.integral, g.extension_code, ".
            " g.is_alone_sale, g.is_shipping, gs.goods_number, g.shop_price ".
            " FROM " .$GLOBALS['ecs']->table('goods'). " AS g ".
            " LEFT JOIN " .$GLOBALS['ecs']->table('goods_stock'). " AS gs ON gs.goods_id = g.goods_id AND gs.area_id = '$_SESSION[area_id]' AND " . ($spec?('gs.goods_attr_id = ' . $spec[0]):'gs.goods_attr_id = 0') .
            " WHERE g.goods_id = '$goods_id'" .
            " AND g.is_delete = 0";
    $goods = $GLOBALS['db']->getRow($sql);

    //判断是否在促销中
    if($goods['promote_start_date']<time()&&$goods['promote_end_date']>time()){
        $goods['goods_number'] = limit_num($goods_id,2);    //闪购库存
        $goods['extension_code']    = "limit";
        $add_time = time();
    }

    if (empty($goods))
    {
        $GLOBALS['err']->add($GLOBALS['_LANG']['goods_not_exists'], ERR_NOT_EXISTS);

        return false;
    }


    /* 是否正在销售 */
    if ($goods['is_on_sale'] == 0)
    {
        $GLOBALS['err']->add($GLOBALS['_LANG']['not_on_sale'], ERR_NOT_ON_SALE);

        return false;
    }

    /* 不是配件时检查是否允许单独销售 */
    if ($goods['is_alone_sale'] == 0)
    {
        $GLOBALS['err']->add($GLOBALS['_LANG']['cannt_alone_sale'], ERR_CANNT_ALONE_SALE);

        return false;
    }
    //检查：商品购买数量是否大于总库存
    if (!$spec && $num > $goods['goods_number'])
    {
        $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['shortage'], $goods['goods_number']), ERR_OUT_OF_STOCK);
        return false;
    }

    /* 计算商品的促销价格 */
    // $spec_price             = spec_price($spec); // 属性价
    // $goods_price            = get_final_price($goods_id, $num, true, $spec); // 商品价格

    /* 扩展属性格式化 */
    if($spec){
        $goods_attr             = get_goods_attr_info($spec); 
        $goods_attr_sku         = get_goods_attr_sku($spec);
        $goods_attr_id          = join(',', $spec);
    }else{
        $goods_attr_id      = 0;
    }

    /* 最组合选择颜色规格格式化 */
    if($attr){
        $goods_attr = array();
        $compose_note = array();
        $number = array();
        foreach (explode(',',$attr) as $key => $value) {
            if(!$value) continue;
            $goods_attr[] = end(explode('-',current(explode('*',$value)))).'*'.end(explode('*',$value));
            $compose_note[] = current(explode('-',current(explode('*',$value)))).'*'.end(explode('*',$value));
        }
    }

    /* 初始化要插入购物车的基本件数据 */
    $parent = array(
        'user_id'         => $_SESSION['user_id'],
        'session_id'      => SESS_ID,
        'goods_id'        => $goods_id,
        'goods_sku'       => addslashes($goods['goods_sku']),
        'product_id'      => $product_info['product_id'],
        'goods_name'      => addslashes($goods['goods_name']),
        'market_price'    => $goods['market_price']>0?$goods['market_price']:$goods['shop_price'],
        'goods_attr'      => $attr?implode(',<br />',$goods_attr):$goods_attr,
        'compose_note'    => $compose_note?implode(',',$compose_note).','.implode(',',array_slice(explode(',',$goods['compose_note']),1)):'',
        'goods_attr_sku'  => $goods_attr_sku,
        'goods_attr_id'   => $goods_attr_id,
        'extension_code'  => $goods['extension_code'],
        'is_gift'         => 0,
        'is_real'         => 1,
        'is_shipping'     => $goods['is_shipping'],
        'rec_type'        => CART_GENERAL_GOODS,
        'area_id'         => $_SESSION['area_id'],
        'add_time'        => !empty($add_time)?$add_time:'0',
    );

    /* 如果数量不为0，作为基本件插入 */
    if ($num > 0)
    {
        /* 检查该商品是否已经存在在购物车中 */
        $sql = "SELECT goods_number FROM " .$GLOBALS['ecs']->table('cart').
                " WHERE (session_id = '" .SESS_ID. "'" . ($_SESSION['user_id']?" OR user_id = $_SESSION[user_id]":'') . ")AND goods_id = '$goods_id' ".
                " AND parent_id = 0 AND goods_attr = '" .$parent['goods_attr']. "' " .
                " AND extension_code <> 'package_buy' " .
                " AND rec_type = '" . CART_GENERAL_GOODS . "' AND extension_code = '".$goods['extension_code'] ."'";

        $row = $GLOBALS['db']->getRow($sql);

        if($row) //如果购物车已经有此物品，则更新
        {
            $num += $row['goods_number'];
            if(is_spec($spec) && !empty($prod) )
            {
                $goods_storage=$product_info['product_number'];
            }
            else
            {
                $goods_storage=$goods['goods_number'];
            }

            if ($GLOBALS['_CFG']['use_storage'] == 0 || $num <= $goods_storage)
            {
                $goods_price = get_final_price($goods_id, $num, true, $spec);
                $sql = "UPDATE " . $GLOBALS['ecs']->table('cart') . " SET goods_number = '$num'" .
                       " , goods_price = '$goods_price' ".
                       " WHERE session_id = '" .SESS_ID. "' AND goods_id = '$goods_id' ".
                       " AND parent_id = 0 AND goods_attr = '" .$parent['goods_attr']. "' " .
                       " AND extension_code <> 'package_buy' " .
                       "AND rec_type = '" . CART_GENERAL_GOODS . "' AND extension_code = '".$goods['extension_code'] ."'";
                $GLOBALS['db']->query($sql);
            }
            else
            {
               $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['shortage'], $num), ERR_OUT_OF_STOCK);

                return false;
            }
        }
        else //购物车没有此物品，则插入
        {
            $goods_price = get_final_price($goods_id, $num, true, $spec);
            $parent['goods_price']  = $goods_price;
            $parent['goods_number'] = $num;
            $parent['parent_id']    = 0;
            $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('cart'), $parent, 'INSERT');
        }
    }

    return true;
}

/* 获取礼包中的商品信息 */
// function get_act_msg($goods_ids, $price, $num){
//     $GLOBALS['err']->clean();

//     /* 取得商品信息 */
//     $sql = "SELECT g.goods_id, g.goods_name, g.goods_weight, g.seller_note, g.goods_sku, g.compose_note, g.is_on_sale,g.seller_note,".
//             "g.market_price, g.promote_price, g.promote_start_date, g.cat_id, g.goods_thumb, ".
//             "g.promote_end_date, g.goods_weight, g.integral, g.extension_code, ".
//             " g.is_alone_sale, g.is_shipping, gs.goods_number AS goods_stock, g.shop_price, g.preferential_price ".
//             " FROM " .$GLOBALS['ecs']->table('goods'). " AS g ".
//             " LEFT JOIN " .$GLOBALS['ecs']->table('goods_stock'). " AS gs ON gs.goods_id = g.goods_id AND gs.area_id = '$_SESSION[area_id]' AND " . ($spec?('gs.goods_attr_id = ' . $spec[0]):'gs.goods_attr_id = 0') .
//             " WHERE g.goods_id IN ($goods_ids)" .
//             " AND g.is_delete = 0";
//     $act_msg = $GLOBALS['db']->getAll($sql);

//     foreach ($act_msg as $key => $value) {
//         $act_msg[$key]['is_gift']   = 0;
//         $act_msg[$key]['is_real']   = 1;
//         $act_msg[$key]['area_id']   = $_SESSION['area_id'];
//         $act_msg[$key]['formated_market_price'] = price_format($value['market_price'], false);
//         $act_msg[$key]['formated_goods_price']  = price_format($value['goods_price'], false);
//         $act_msg[$key]['formated_subtotal']     = price_format($value['subtotal'], false);
//         $act_msg[$key]['goods_buy_num']     = $num;       // 礼包商品的数量
//         $act_msg[$key]['goods_buy_price']   = $price;     // 礼包商品的价格
//         $act_msg[$key]['is_imme_checkout']  = 1;
//         // 判断商品库存是否足够
//         if( $act_msg[$key]['goods_stock'] >= $act_msg[$key]['goods_buy_num']){
//             $act_msg[$key]['is_buy'] = 1;
//         }else{
//             $act_msg[$key]['is_buy'] = 0;
//         }
//     }

//     return $act_msg;
// }

/* 添加礼包到购物车 */
function activityToCart($parent_id = 0, $number = 0){
    if($parent_id && $number > 0){
        /* 查询礼包信息 */
        $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('activity') . " WHERE parent_id = '$parent_id'";
        $info = $GLOBALS['db']->getRow($sql);
        if(!$info){
            $GLOBALS['err']->add('未找到相关礼包信息！', 1);
            return false;
        }elseif($info['is_sale'] != 1){
            $GLOBALS['err']->add('当前礼包已停止销售，敬请期待！',1);
            return false;
        }
        /* 查询礼包当前可购买数量 */
        $area_id = $_SESSION['area_id'] ? $_SESSION['area_id'] : 3;
        $sql = "SELECT valid_number FROM " . $GLOBALS['ecs']->table('activity_stock') . " WHERE parent_id = '$parent_id' AND area_id = '$area_id'";
        $info['valid_number'] = $GLOBALS['db']->getOne($sql);
        if(empty($info['valid_number']) || $info['valid_number'] < $number){
            if(empty($info['valid_number'])){
                $GLOBALS['err']->add('礼包已被抢光！');
            }else{
                $GLOBALS['err']->add('礼包数量不足，还剩'.$info['valid_number'].'件！');
            }
            return false;
        }
        /* 查询购物车是否已存在该礼包 */
        $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('cart') . " WHERE parent_id = '$parent_id' AND goods_id = 0 AND user_id = '$_SESSION[user_id]'";
        $cartInfo = $GLOBALS['db']->getRow($sql);
        if($cartInfo){
             /* 查询礼包商品具体信息 */
            $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('activity_goods') . " WHERE parent_id = '$parent_id'";
            $goodsList = $GLOBALS['db']->getAll($sql);
            foreach ($goodsList as $key => $value) {
                $goods_number = $value['goods_number'] * $number;
                $sql = "UPDATE " . $GLOBALS['ecs']->table('cart') . " SET goods_number = goods_number + $goods_number WHERE goods_id = $value[goods_id] AND goods_attr_id = $value[goods_attr_id] AND parent_id = $parent_id";
                $GLOBALS['db']->query($sql);
            }
            // 更新购物车显示的礼包数量
            $sql = "UPDATE " . $GLOBALS['ecs']->table('cart') . " SET goods_number = goods_number + $number WHERE goods_id = '0' AND goods_attr_id = '0' AND parent_id = $parent_id";
            $GLOBALS['db']->query($sql);
        }else{
            /* 查询礼包商品信息 */
            $sql = "SELECT ag.goods_number, g.goods_id, g.goods_sku, g.goods_name, g.market_price, g.shop_price, ga.goods_attr_id, ga.attr_sku AS goods_attr_sku, ga.attr_value AS goods_attr FROM " . $GLOBALS['ecs']->table('activity_goods') . " ag LEFT JOIN " . $GLOBALS['ecs']->table('goods') . " g ON g.goods_id = ag.goods_id LEFT JOIN " . $GLOBALS['ecs']->table('goods_attr') . " ga ON ga.goods_attr_id = ag.goods_attr_id WHERE parent_id = '$parent_id'";
            $goodsList = $GLOBALS['db']->getAll($sql);
            foreach ($goodsList as $key => $value) {
                $parent                   = $value;
                $parent['extension_code'] = $info['extension_code'];
                $parent['parent_id']      = $info['parent_id'];
                $parent['add_time']       = time();
                $parent['user_id']        = $_SESSION['user_id'];
                $parent['session_id']     = SESS_ID;
                $parent['area_id']        = $area_id;
                $parent['rec_type']       = CART_GENERAL_GOODS;
                $parent['is_real']        = 1;
                $parent['goods_price']    = $value['shop_price']*($info['original_price']?($info['price']/$info['original_price']):0.8);
                $parent['goods_number']   = $value['goods_number'] * $number;
                $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('cart'), $parent, 'INSERT');
                unset($parent);
            }
            /* 初始化要插入购物车的数据 */
            $parent = array(
                'user_id'        => $_SESSION['user_id'],
                'session_id'     => SESS_ID,
                'goods_id'       => 0,
                'goods_sku'      => 0,
                'product_id'     => 0,
                'goods_name'     => $info['name'],
                'market_price'   => $info['original_price'],
                'goods_attr_sku' => 0,
                'goods_attr_id'  => 0,
                'extension_code' => $info['extension_code'],
                'is_gift'        => 0,
                'is_real'        => 0,
                'is_shipping'    => 0,
                'rec_type'       => CART_GENERAL_GOODS,
                'area_id'        => $area_id,
                'add_time'       => time(),
                'goods_price'    => $info['price'],
                'goods_number'   => $number,
                'parent_id'      => $info['parent_id'],
            );
            $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('cart'), $parent, 'INSERT');
            unset($parent);
        }
        /* 修改礼包数量 */
        $sql = "UPDATE " . $GLOBALS['ecs']->table('activity_stock') . " SET valid_number = valid_number - $number, cart_number = cart_number + $number WHERE parent_id = '$parent_id' AND area_id = '$area_id'";
        $GLOBALS['db']->query($sql);
        return true;
    }
}

/**
 * 删除购物车礼包信息
 */
function activityDeleteCart($rec_id){

    if($rec_id && $_SESSION['user_id']){
        // 查询礼包是否存在
        $sql = "SELECT parent_id, goods_id, goods_number, area_id FROM " . $GLOBALS['ecs']->table('cart') . " WHERE rec_id = '$rec_id' AND user_id = '$_SESSION[user_id]' AND goods_id = 0";
        $cart = $GLOBALS['db']->getRow($sql);
        if(!$cart){
            $GLOBALS['err']->add("未找到此礼包信息");
            return false;
        }else{
            /* 删除用户购物车礼包信息 */
            $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') . " WHERE parent_id = '$cart[parent_id]' AND user_id = '$_SESSION[user_id]'";
            $GLOBALS['db']->query($sql);
            /* 更新礼包数量 */
            $sql = "UPDATE " . $GLOBALS['ecs']->table('activity_stock') . " SET valid_number = valid_number + $cart[goods_number], cart_number = cart_number - $cart[goods_number] WHERE parent_id = '$cart[parent_id]' AND area_id = '$cart[area_id]'";
            $GLOBALS['db']->query($sql);
            return true;
        }
    }else{
        $GLOBALS['err']->add("参数错误，请联系管理员进行处理！");
        return false;
    }
}

/**
 * 清空购物车无效礼包
 * $isLock 是否直接加锁处理
 */
function clearActivityCart($isLock = false){
    // 查询礼包是否存在
    $oldTime = time()-2*3600;
    if($isLock){
        // 加锁
        require_once(ROOT_PATH . 'includes/cls_cachelock.php');
        $lock = new CacheLock('lock_order_done','lock_order_done');
        $lock2 = new CacheLock('lock_add_to_cart','lock_add_to_cart');
        $lock->lock();
        $lock2->lock();
        // 查询超时礼包
        $sql = "SELECT rec_id, parent_id, goods_id, goods_number, area_id, user_id FROM " . $GLOBALS['ecs']->table('cart') . " WHERE extension_code = 'libao' AND goods_id = 0 AND add_time < $oldTime";
        $cart = $GLOBALS['db']->getAll($sql);
        if($cart){
            $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') . " WHERE extension_code = 'libao' AND add_time < $oldTime";
            $GLOBALS['db']->query($sql);
            foreach ($cart as $key => $value) {
                /* 更新礼包数量 */
                $sql = "UPDATE " . $GLOBALS['ecs']->table('activity_stock') . " SET valid_number = valid_number + $value[goods_number], cart_number = cart_number - $value[goods_number] WHERE parent_id = '$value[parent_id]' AND area_id = '$value[area_id]'";
                $GLOBALS['db']->query($sql);
            }
        }
        // 释放锁
        $lock->unlock();
        $lock2->unlock();
    }else{
        // 查询超时礼包
        $sql = "SELECT rec_id, parent_id, goods_id, goods_number, area_id, user_id FROM " . $GLOBALS['ecs']->table('cart') . " WHERE extension_code = 'libao' AND goods_id = 0 AND add_time < $oldTime";
        $cart = $GLOBALS['db']->getAll($sql);
        if($cart){
            clearActivityCart(true);
        }
    }
}

/**
 * 清空购物车中没有被勾选的商品
 * @param   int     $type   类型：默认普通商品
 */
function clear_cart($type = CART_GENERAL_GOODS, $rec_id)
{
    $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') .
            " WHERE (session_id = '" . SESS_ID . "'" . ($_SESSION['user_id']?" OR user_id = $_SESSION[user_id]":'')  . ")  AND rec_type = '$type'".(!empty($rec_id)?" AND rec_id IN ($rec_id)":'');
    $GLOBALS['db']->query($sql);
}

/**
 * 获得指定的商品属性
 *
 * @access      public
 * @param       array       $arr        规格、属性ID数组
 * @param       type        $type       设置返回结果类型：pice，显示价格，默认；no，不显示价格
 *
 * @return      string
 */
function get_goods_attr_info($arr, $type = 'pice')
{
    $attr   = '';

    if (!empty($arr))
    {
        //$fmt = "%s:%s[%s] \n";
        $fmt = "%s:%s \n";

        $sql = "SELECT a.attr_name, ga.attr_value, ga.attr_price ".
                "FROM ".$GLOBALS['ecs']->table('goods_attr')." AS ga, ".
                    $GLOBALS['ecs']->table('attribute')." AS a ".
                "WHERE " .db_create_in($arr, 'ga.goods_attr_id')." AND a.attr_id = ga.attr_id AND a.attr_id = 1 ";
        $res = $GLOBALS['db']->query($sql);

        while ($row = $GLOBALS['db']->fetchRow($res))
        {
            $attr_price = round(floatval($row['attr_price']), 2);
            //$attr .= sprintf($fmt, $row['attr_name'], $row['attr_value'], $attr_price);
            $attr .= $row['attr_value'];
        }
    }

    return $attr;
}

/**
 * 获得指定的商品属性SKU编号
 *
 * @access      public
 * @param       array       $arr        规格、属性ID数组
 * @param       type        $type       设置返回结果类型：pice，显示价格，默认；no，不显示价格
 *
 * @return      string
 */
function get_goods_attr_sku($arr, $type = 'pice')
{
    $attr   = '';

    if (!empty($arr))
    {
        //$fmt = "%s:%s[%s] \n";
        $fmt = "%s:%s \n";

        $sql = "SELECT a.attr_name, ga.attr_value,ga.attr_sku, ga.attr_price ".
                "FROM ".$GLOBALS['ecs']->table('goods_attr')." AS ga, ".
                    $GLOBALS['ecs']->table('attribute')." AS a ".
                "WHERE " .db_create_in($arr, 'ga.goods_attr_id')." AND a.attr_id = ga.attr_id AND a.attr_id = 1 ";
        $res = $GLOBALS['db']->query($sql);

        while ($row = $GLOBALS['db']->fetchRow($res))
        {
            $attr_price = round(floatval($row['attr_price']), 2);
            //$attr .= sprintf($fmt, $row['attr_name'], $row['attr_value'], $attr_price);
            $attr .= $row['attr_sku'];
        }
    }
    return $attr;
}

/**
 * 取得用户信息
 * @param   int     $user_id    用户id
 * @return  array   用户信息
 */
function user_info($user_id)
{
    $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('users') .
            " WHERE user_id = '$user_id'";
    $user = $GLOBALS['db']->getRow($sql);

    unset($user['question']);
    unset($user['answer']);

    /* 格式化帐户余额 */
    if ($user)
    {
//        if ($user['user_money'] < 0)
//        {
//            $user['user_money'] = 0;
//        }
        $user['formated_user_money'] = price_format($user['user_money'], false);
        $user['formated_frozen_money'] = price_format($user['frozen_money'], false);
    }

    return $user;
}

/**
 * 修改用户
 * @param   int     $user_id   订单id
 * @param   array   $user      key => value
 * @return  bool
 */
function update_user($user_id, $user)
{
    return $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('users'),
        $user, 'UPDATE', "user_id = '$user_id'");
}

/**
 * 取得用户地址列表
 * @param   int     $user_id    用户id
 * @return  array
 */
function address_list($user_id)
{
    $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('user_address') .
            " WHERE user_id = '$user_id'";

    return $GLOBALS['db']->getAll($sql);
}

/**
 * 取得用户地址信息
 * @param   int     $address_id     地址id
 * @return  array
 */
function address_info($address_id)
{
    $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('user_address') .
            " WHERE address_id = '$address_id'";

    return $GLOBALS['db']->getRow($sql);
}

/**
 * 取得用户当前可用红包
 * @param   int     $user_id        用户id
 * @param   float   $goods_amount   订单商品金额
 * @return  array   红包数组
 */
function user_bonus($user_id, $goods_amount = 0)
{
    $day    = getdate();
    $today  = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);

    $sql = "SELECT t.type_id, t.type_name, t.type_money, b.bonus_id " .
            "FROM " . $GLOBALS['ecs']->table('bonus_type') . " AS t," .
                $GLOBALS['ecs']->table('user_bonus') . " AS b " .
            "WHERE t.type_id = b.bonus_type_id " .
            "AND t.use_start_date <= '$today' " .
            "AND t.use_end_date >= '$today' " .
            "AND t.min_goods_amount <= '$goods_amount' " .
            "AND b.user_id<>0 " .
            "AND b.user_id = '$user_id' " .
            "AND b.order_id = 0";
    return $GLOBALS['db']->getAll($sql);
}

/**
 * 取得红包信息
 * @param   int     $bonus_id   红包id
 * @param   string  $bonus_sn   红包序列号
 * @param   array   红包信息
 */
function bonus_info($bonus_id, $bonus_sn = '')
{
    $sql = "SELECT t.*, b.* " .
            "FROM " . $GLOBALS['ecs']->table('bonus_type') . " AS t," .
                $GLOBALS['ecs']->table('user_bonus') . " AS b " .
            "WHERE t.type_id = b.bonus_type_id ";
    if ($bonus_id > 0)
    {
        $sql .= "AND b.bonus_id = '$bonus_id'";
    }
    else
    {
        $sql .= "AND b.bonus_sn = '$bonus_sn'";
    }

    return $GLOBALS['db']->getRow($sql);
}

/**
 * 检查红包是否已使用
 * @param   int $bonus_id   红包id
 * @return  bool
 */
function bonus_used($bonus_id)
{
    $sql = "SELECT order_id FROM " . $GLOBALS['ecs']->table('user_bonus') .
            " WHERE bonus_id = '$bonus_id'";

    return  $GLOBALS['db']->getOne($sql) > 0;
}

/**
 * 设置红包为已使用
 * @param   int     $bonus_id   红包id
 * @param   int     $order_id   订单id
 * @return  bool
 */
function use_bonus($bonus_id, $order_id)
{
    $sql = "UPDATE " . $GLOBALS['ecs']->table('user_bonus') .
            " SET order_id = '$order_id', used_time = '" . gmtime() . "' " .
            "WHERE bonus_id = '$bonus_id' LIMIT 1";

    return  $GLOBALS['db']->query($sql);
}

/**
 * 设置红包为未使用
 * @param   int     $bonus_id   红包id
 * @param   int     $order_id   订单id
 * @return  bool
 */
function unuse_bonus($bonus_id)
{
    $sql = "UPDATE " . $GLOBALS['ecs']->table('user_bonus') .
            " SET order_id = 0, used_time = 0 " .
            "WHERE bonus_id = '$bonus_id' LIMIT 1";

    return  $GLOBALS['db']->query($sql);
}

/**
 * 计算积分的价值（能抵多少钱）
 * @param   int     $integral   积分
 * @return  float   积分价值
 */
function value_of_integral($integral)
{
    $scale = floatval($GLOBALS['_CFG']['integral_scale']);

    return $scale > 0 ? round(($integral / 100) * $scale, 2) : 0;
}

/**
 * 计算指定的金额需要多少积分
 *
 * @access  public
 * @param   integer $value  金额
 * @return  void
 */
function integral_of_value($value)
{
    $scale = floatval($GLOBALS['_CFG']['integral_scale']);

    return $scale > 0 ? round($value / $scale * 100) : 0;
}

/**
 * 订单退款
 * @param   array   $order          订单
 * @param   int     $refund_type    退款方式 1 到帐户余额 2 到退款申请（先到余额，再申请提款） 3 不处理
 * @param   string  $refund_note    退款说明
 * @param   float   $refund_amount  退款金额（如果为0，取订单已付款金额）
 * @return  bool
 */
function order_refund($order, $refund_type, $refund_note, $refund_amount = 0)
{
    /* 检查参数 */
    $user_id = $order['user_id'];
    if ($user_id == 0 && $refund_type == 1)
    {
        die('anonymous, cannot return to account balance');
    }

    $amount = $refund_amount > 0 ? $refund_amount : $order['money_paid'];
    if ($amount <= 0)
    {
        return true;
    }

    if (!in_array($refund_type, array(1, 2, 3)))
    {
        die('invalid params');
    }

    /* 备注信息 */
    if ($refund_note)
    {
        $change_desc = $refund_note;
    }
    else
    {
        include_once(ROOT_PATH . 'languages/' .$GLOBALS['_CFG']['lang']. '/admin/order.php');
        $change_desc = sprintf($GLOBALS['_LANG']['order_refund'], $order['order_sn']);
    }

    /* 处理退款 */
    if (1 == $refund_type)
    {
        log_account_change($user_id, $amount, 0, 0, 0, $change_desc);

        return true;
    }
    elseif (2 == $refund_type)
    {
        /* 如果非匿名，退回余额 */
        if ($user_id > 0)
        {
            log_account_change($user_id, $amount, 0, 0, 0, $change_desc);
        }

        /* user_account 表增加提款申请记录 */
        $account = array(
            'user_id'      => $user_id,
            'amount'       => (-1) * $amount,
            'add_time'     => gmtime(),
            'user_note'    => $refund_note,
            'process_type' => SURPLUS_RETURN,
            'admin_user'   => $_SESSION['admin_name'],
            'admin_note'   => sprintf($GLOBALS['_LANG']['order_refund'], $order['order_sn']),
            'is_paid'      => 0
        );
        $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('user_account'), $account, 'INSERT');

        return true;
    }
    else
    {
        return true;
    }
}

/**
 * 获得购物车中的商品
 *
 * @access  public
 * @return  array
 */
function get_cart_goods()
{
    /* 初始化 */
    $goods_list = array();
    $total = array(
        'goods_price'  => 0, // 本店售价合计（有格式）
        'market_price' => 0, // 市场售价合计（有格式）
        'saving'       => 0, // 节省金额（有格式）
        'save_rate'    => 0, // 节省百分比
        'goods_amount' => 0, // 本店售价合计（无格式）
    );
    $user_id = $_SESSION['user_id']?$_SESSION['user_id']:0;
    /* 循环、统计 */
    $sql = "SELECT g.goods_thumb,g.promote_start_date,g.promote_end_date,g.seller_note, gs.goods_number AS goods_stock, c.*, IF(c.parent_id, c.parent_id, c.goods_id) AS pid " .
            " FROM " . $GLOBALS['ecs']->table('cart') . " c ".
            " LEFT JOIN " . $GLOBALS['ecs']->table('goods') . " g ON(g.goods_id = c.goods_id) " .
            " LEFT JOIN " . $GLOBALS['ecs']->table('goods_stock') . " gs ON(gs.goods_id = c.goods_id AND gs.goods_attr_id = c.goods_attr_id AND gs.area_id = 3) ".
            " WHERE (c.session_id = '" . SESS_ID . "' " . ($user_id?" OR c.user_id = $user_id":'') . ") AND c.rec_type = '" . CART_GENERAL_GOODS . "'" .
            " ORDER BY pid, c.parent_id";
    
    $res = $GLOBALS['db']->query($sql);

    /* 用于统计购物车中实体商品和虚拟商品的个数 */
    $virtual_goods_count = 0;
    $real_goods_count    = 0;

    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        if($row['promote_start_date']<time()&&time()<$row['promote_end_date']&&!empty($row['seller_note'])){
            if($row['goods_stock']>$row['seller_note']){
                $row['goods_stock']=$row['seller_note'];
            }
        }




        $total['goods_price']  += $row['goods_price'] * $row['goods_number'];
        $total['market_price'] += $row['market_price'] * $row['goods_number'];

        $row['subtotal']     = price_format($row['goods_price'] * $row['goods_number'], false);
        $row['goods_price']  = price_format($row['goods_price'], false);
        $row['market_price'] = price_format($row['market_price'], false);

        /* 统计实体商品和虚拟商品的个数 */
        if ($row['is_real'])
        {
            $real_goods_count++;
        }
        else
        {
            $virtual_goods_count++;
        }

        /* 查询规格 */
        if (trim($row['goods_attr']) != '')
        {
            $row['goods_attr']=addslashes($row['goods_attr']);
            $sql = "SELECT attr_value FROM " . $GLOBALS['ecs']->table('goods_attr') . " WHERE goods_attr_id " .
            db_create_in($row['goods_attr']);
            $attr_list = $GLOBALS['db']->getCol($sql);
        }
        if ($row['extension_code'] == 'package_buy')
        {
            $row['package_goods_list'] = get_package_goods($row['goods_id']);
        }
        $goods_list[] = $row;
    }
    $total['goods_amount'] = $total['goods_price'];
    $total['saving']       = price_format($total['market_price'] - $total['goods_price'], false);
    if ($total['market_price'] > 0)
    {
        $total['save_rate'] = $total['market_price'] ? round(($total['market_price'] - $total['goods_price']) *
        100 / $total['market_price']).'%' : 0;
    }
    $total['goods_price']  = price_format($total['goods_price'], false);
    $total['market_price'] = price_format($total['market_price'], false);
    $total['real_goods_count']    = $real_goods_count;
    $total['virtual_goods_count'] = $virtual_goods_count;

    return array('goods_list' => $goods_list, 'total' => $total);
}





/**
 * 取得收货人信息
 * @param   int     $user_id    用户编号
 * @return  array
 */
function get_consignee($user_id)
{
    if (isset($_SESSION['flow_consignee']))
    {
        /* 如果存在session，则直接返回session中的收货人信息 */

        return $_SESSION['flow_consignee'];
    }
    else
    {
        /* 如果不存在，则取得用户的默认收货人信息 */
        $arr = array();

        if ($user_id > 0)
        {
            /* 取默认地址 */
            $sql = "SELECT ua.*".
                    " FROM " . $GLOBALS['ecs']->table('user_address') . "AS ua, ".$GLOBALS['ecs']->table('users').' AS u '.
                    " WHERE u.user_id='$user_id' AND ua.address_id = u.address_id";

            $arr = $GLOBALS['db']->getRow($sql);
        }

        return $arr;
    }
}

/**
 * 查询购物车（订单id为0）或订单中是否有实体商品
 * @param   int     $order_id   订单id
 * @param   int     $flow_type  购物流程类型
 * @return  bool
 */
function exist_real_goods($order_id = 0, $flow_type = CART_GENERAL_GOODS)
{
    if ($order_id <= 0)
    {
        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('cart') .
                " WHERE session_id = '" . SESS_ID . "' AND is_real != 2 " .
                "AND rec_type = '$flow_type'";
    }
    else
    {
        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('order_goods') .
                " WHERE order_id = '$order_id' AND is_real != 2";
    }

    return $GLOBALS['db']->getOne($sql) > 0;
}

/**
 * 检查收货人信息是否完整
 * @param   array   $consignee  收货人信息
 * @param   int     $flow_type  购物流程类型
 * @return  bool    true 完整 false 不完整
 */
function check_consignee_info($consignee, $flow_type)
{
    if (exist_real_goods(0, $flow_type))
    {
        /* 如果存在实体商品 */
        $res = !empty($consignee['country']);

        if ($res)
        {
            if (empty($consignee['province']))
            {
                /* 没有设置省份，检查当前国家下面有没有设置省份 */
                $pro = get_regions(1, $consignee['country']);
                $res = empty($pro);
            }
            elseif (empty($consignee['city']))
            {
                /* 没有设置城市，检查当前省下面有没有城市 */
                $city = get_regions(2, $consignee['province']);
                $res = empty($city);
            }
            elseif (empty($consignee['district']))
            {
                $dist = get_regions(3, $consignee['city']);
                $res = empty($dist);
            }
        }

        return $res;
    }
    else
    {
        /* 如果不存在实体商品 */
        return !empty($consignee);
    }
}

/**
 * 获得上一次用户采用的支付和配送方式
 *
 * @access  public
 * @return  void
 */
function last_shipping_and_payment()
{
    $sql = "SELECT shipping_id, pay_id " .
            " FROM " . $GLOBALS['ecs']->table('order_info') .
            " WHERE user_id = '$_SESSION[user_id]' " .
            " ORDER BY order_id DESC LIMIT 1";
    $row = $GLOBALS['db']->getRow($sql);

    if (empty($row))
    {
        /* 如果获得是一个空数组，则返回默认值 */
        $row = array('shipping_id' => 0, 'pay_id' => 0);
    }

    return $row;
}

/**
 * 取得当前用户应该得到的红包总额
 */
function get_total_bonus()
{
    $day    = getdate();
    $today  = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);

    /* 按商品发的红包 */
    $sql = "SELECT SUM(c.goods_number * t.type_money)" .
            "FROM " . $GLOBALS['ecs']->table('cart') . " AS c, "
                    . $GLOBALS['ecs']->table('bonus_type') . " AS t, "
                    . $GLOBALS['ecs']->table('goods') . " AS g " .
            "WHERE c.session_id = '" . SESS_ID . "' " .
            "AND c.is_gift = 0 " .
            "AND c.goods_id = g.goods_id " .
            "AND g.bonus_type_id = t.type_id " .
            "AND t.send_type = '" . SEND_BY_GOODS . "' " .
            "AND t.send_start_date <= '$today' " .
            "AND t.send_end_date >= '$today' " .
            "AND c.rec_type = '" . CART_GENERAL_GOODS . "'";
    $goods_total = floatval($GLOBALS['db']->getOne($sql));

    /* 取得购物车中非赠品总金额 */
    $sql = "SELECT SUM(goods_price * goods_number) " .
            "FROM " . $GLOBALS['ecs']->table('cart') .
            " WHERE session_id = '" . SESS_ID . "' " .
            " AND is_gift = 0 " .
            " AND rec_type = '" . CART_GENERAL_GOODS . "'";
    $amount = floatval($GLOBALS['db']->getOne($sql));

    /* 按订单发的红包 */
    $sql = "SELECT FLOOR('$amount' / min_amount) * type_money " .
            "FROM " . $GLOBALS['ecs']->table('bonus_type') .
            " WHERE send_type = '" . SEND_BY_ORDER . "' " .
            " AND send_start_date <= '$today' " .
            "AND send_end_date >= '$today' " .
            "AND min_amount > 0 ";
    $order_total = floatval($GLOBALS['db']->getOne($sql));

    return $goods_total + $order_total;
}

/**
 * 处理红包（下订单时设为使用，取消（无效，退货）订单时设为未使用
 * @param   int     $bonus_id   红包编号
 * @param   int     $order_id   订单号
 * @param   int     $is_used    是否使用了
 */
function change_user_bonus($bonus_id, $order_id, $is_used = true)
{
    if ($is_used)
    {
        $sql = 'UPDATE ' . $GLOBALS['ecs']->table('user_bonus') . ' SET ' .
                'used_time = ' . gmtime() . ', ' .
                "order_id = '$order_id' " .
                "WHERE bonus_id = '$bonus_id'";
    }
    else
    {
        $sql = 'UPDATE ' . $GLOBALS['ecs']->table('user_bonus') . ' SET ' .
                'used_time = 0, ' .
                'order_id = 0 ' .
                "WHERE bonus_id = '$bonus_id'";
    }
    $GLOBALS['db']->query($sql);
}

/**
 * 获得订单信息
 *
 * @access  private
 * @return  array
 */
function flow_order_info()
{
    $order = isset($_SESSION['flow_order']) ? $_SESSION['flow_order'] : array();

    /* 初始化配送和支付方式 */
    if (!isset($order['shipping_id']) || !isset($order['pay_id']))
    {
        /* 如果还没有设置配送和支付 */
        if ($_SESSION['user_id'] > 0)
        {
            /* 用户已经登录了，则获得上次使用的配送和支付 */
            $arr = last_shipping_and_payment();

            if (!isset($order['shipping_id']))
            {
                $order['shipping_id'] = $arr['shipping_id'];
            }
            if (!isset($order['pay_id']))
            {
                $order['pay_id'] = $arr['pay_id'];
            }
        }
        else
        {
            if (!isset($order['shipping_id']))
            {
                $order['shipping_id'] = 0;
            }
            if (!isset($order['pay_id']))
            {
                $order['pay_id'] = 0;
            }
        }
    }


    if (!isset($order['bonus']))
    {
        $order['bonus'] = 0;    // 初始化红包
    }
    if (!isset($order['integral']))
    {
        $order['integral'] = 0; // 初始化积分
    }

    $order['pay_id'] = 1; // 强制默认使用支付宝支付
    return $order;
}

/**
 * 合并订单
 * @param   string  $from_order_sn  从订单号
 * @param   string  $to_order_sn    主订单号
 * @return  成功返回true，失败返回错误信息
 */
function merge_order($from_order_sn, $to_order_sn)
{
    /* 订单号不能为空 */
    if (trim($from_order_sn) == '' || trim($to_order_sn) == '')
    {
        return $GLOBALS['_LANG']['order_sn_not_null'];
    }

    /* 订单号不能相同 */
    if ($from_order_sn == $to_order_sn)
    {
        return $GLOBALS['_LANG']['two_order_sn_same'];
    }

    /* 取得订单信息 */
    $from_order = order_info(0, $from_order_sn);
    $to_order   = order_info(0, $to_order_sn);

    /* 检查订单是否存在 */
    if (!$from_order)
    {
        return sprintf($GLOBALS['_LANG']['order_not_exist'], $from_order_sn);
    }
    elseif (!$to_order)
    {
        return sprintf($GLOBALS['_LANG']['order_not_exist'], $to_order_sn);
    }

    /* 检查合并的订单是否为普通订单，非普通订单不允许合并 */
    if ($from_order['extension_code'] != '' || $to_order['extension_code'] != 0)
    {
        return $GLOBALS['_LANG']['merge_invalid_order'];
    }

    /* 检查订单状态是否是已确认或未确认、未付款、未发货 */
    if ($from_order['order_status'] != OS_UNCONFIRMED && $from_order['order_status'] != OS_CONFIRMED)
    {
        return sprintf($GLOBALS['_LANG']['os_not_unconfirmed_or_confirmed'], $from_order_sn);
    }
    elseif ($from_order['pay_status'] != PS_UNPAYED)
    {
        return sprintf($GLOBALS['_LANG']['ps_not_unpayed'], $from_order_sn);
    }
    elseif ($from_order['shipping_status'] != SS_UNSHIPPED)
    {
        return sprintf($GLOBALS['_LANG']['ss_not_unshipped'], $from_order_sn);
    }

    if ($to_order['order_status'] != OS_UNCONFIRMED && $to_order['order_status'] != OS_CONFIRMED)
    {
        return sprintf($GLOBALS['_LANG']['os_not_unconfirmed_or_confirmed'], $to_order_sn);
    }
    elseif ($to_order['pay_status'] != PS_UNPAYED)
    {
        return sprintf($GLOBALS['_LANG']['ps_not_unpayed'], $to_order_sn);
    }
    elseif ($to_order['shipping_status'] != SS_UNSHIPPED)
    {
        return sprintf($GLOBALS['_LANG']['ss_not_unshipped'], $to_order_sn);
    }

    /* 检查订单用户是否相同 */
    if ($from_order['user_id'] != $to_order['user_id'])
    {
        return $GLOBALS['_LANG']['order_user_not_same'];
    }


    $to_goods_list = order_goods($to_order['order_id']);
    $from_goods_list = order_goods($from_order['order_id']);
    $goods_list = array_merge($to_goods_list,$from_goods_list);
    $total = order_fee($to_order, $goods_list, $to_order);

    /* 合并订单 */
    $order = $to_order;
    $order['order_id']  = '';
    $order['add_time']  = time();

    // 合并商品总额
    $order['goods_amount'] += $from_order['goods_amount'];

    // 合并折扣
    $order['discount'] += $from_order['discount'];

    $order['shipping_fee'] = $total['shipping_fee'];

    // 红包不变，合并积分、余额、已付款金额
    $order['integral']      += $from_order['integral'];
    $order['money_paid']    += $from_order['money_paid'];

    // 计算应付款金额（不包括支付费用）
    $order['order_amount'] = $order['goods_amount'] - $order['discount']
                           + $order['shipping_fee']
                           - $order['money_paid'];
    $order['order_status'] = $order['pay_status'] = $order['shipping_status'] = 0;
    // /* 插入订单表 */
    do
    {
        $order['order_sn'] = get_order_sn();
        if ($GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('order_info'), addslashes_deep($order), 'INSERT'))
        {
            break;
        }
        else
        {
            if ($GLOBALS['db']->errno() != 1062)
            {
                die($GLOBALS['db']->errorMsg());
            }
        }
    }
    while (true); // 防止订单号重复

    /* 订单号 */
    $order_id = $order['order_id'] = $GLOBALS['db']->insert_id();

    /* 更新订单商品 */
    $sql = 'UPDATE ' . $GLOBALS['ecs']->table('order_goods') .
            " SET order_id = '$order_id' " .
            "WHERE order_id " . db_create_in(array($from_order['order_id'], $to_order['order_id']));
    $GLOBALS['db']->query($sql);
    /* 插入支付日志 */
    $sql = 'INSERT INTO ' .$GLOBALS['ecs']->table('pay_log')." (order_id, order_amount, order_type, is_paid)".
            " VALUES  ('$order_id', '$order[order_amount]', '".PAY_ORDER."', '0')";
    $GLOBALS['db']->query($sql);

    order_receive_freeplan($to_order, 2);
    order_receive_freeplan($from_order, 2);
    order_receive_freeplan($order);
    $sn_list[] = $to_order['order_sn'];
    $sn_list[] = $from_order['order_sn'];
    if(!empty($sn_list)){
        require_once(ROOT_PATH . 'includes/lib_wangcang.php');
        vgetcancelTrade($sn_list, $v_data);
    }

    /* 删除原订单 */
    $sql = 'DELETE FROM ' . $GLOBALS['ecs']->table('order_info') .
            " WHERE order_id " . db_create_in(array($from_order['order_id'], $to_order['order_id']));
    $GLOBALS['db']->query($sql);

    /* 删除原订单支付日志 */
    $sql = 'DELETE FROM ' . $GLOBALS['ecs']->table('pay_log') .
            " WHERE order_id " . db_create_in(array($from_order['order_id'], $to_order['order_id']));
    $GLOBALS['db']->query($sql);

    /* 返回成功 */
    return true;
}

/**
 * 查询配送区域属于哪个办事处管辖
 * @param   array   $regions    配送区域（1、2、3、4级按顺序）
 * @return  int     办事处id，可能为0
 */
function get_agency_by_regions($regions)
{
    if (!is_array($regions) || empty($regions))
    {
        return 0;
    }

    $arr = array();
    $sql = "SELECT region_id, agency_id " .
            "FROM " . $GLOBALS['ecs']->table('region') .
            " WHERE region_id " . db_create_in($regions) .
            " AND region_id > 0 AND agency_id > 0";
    $res = $GLOBALS['db']->query($sql);
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $arr[$row['region_id']] = $row['agency_id'];
    }
    if (empty($arr))
    {
        return 0;
    }

    $agency_id = 0;
    for ($i = count($regions) - 1; $i >= 0; $i--)
    {
        if (isset($arr[$regions[$i]]))
        {
            return $arr[$regions[$i]];
        }
    }
}

/**
 * 获取配送插件的实例
 * @param   int   $shipping_id    配送插件ID
 * @return  object     配送插件对象实例
 */
function &get_shipping_object($shipping_id)
{
    $shipping  = shipping_info($shipping_id);
    if (!$shipping)
    {
        $object = new stdClass();
        return $object;
    }

    $file_path = ROOT_PATH.'includes/modules/shipping/' . $shipping['shipping_code'] . '.php';

    include_once($file_path);

    $object = new $shipping['shipping_code'];
    return $object;
}

/**
 * 改变订单中商品库存
 * @param   int     $order_id   订单号
 * @param   bool    $is_dec     是否减少库存
 * @param   bool    $storage     减库存的时机，1，下订单时；0，发货时；
 */
function change_order_goods_storage($order_id, $is_dec = true, $storage = 0)
{
    /* 查询订单信息 */
    $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('order_info') . " WHERE order_id = '$order_id'";
    $order = $GLOBALS['db']->getRow($sql);
    /* 查询订单商品信息 */
    $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('order_goods') . " WHERE order_id = '$order_id'";
    $order_goods = $GLOBALS['db']->getAll($sql);
    foreach($order_goods AS $key => $value){
        //闪购商品处理
        if($value['extension_code']=="limit"){
                if ($is_dec)
                {
                    limit_goods_storage($value['goods_sku'],$order['agency_id'],$value['goods_number']); 
                    //判断闪购库存是否售完
                    $sql =  " SELECT MAX(goods_num - buy_num) AS num FROM ". $GLOBALS['ecs']->table('limit') ." AS l ".
                            " WHERE l.start_time <= ".time()." AND l.end_time >= ".time()." AND l.goods_sku = '".$value['goods_sku']."' " ;
                    $num = $GLOBALS['db']->getOne($sql);
                    //已售完则更新促销时间
                    if($num<=0){
                            $sql =  " UPDATE ".$GLOBALS['ecs']->table('goods').
                                    " SET promote_end_date = '".time()."'".
                                    " WHERE goods_sku = '".$value['goods_sku']."'";
                            $GLOBALS['db']->query($sql);
                    }
                }
                else
                {
                    change_goods_storage($value['goods_sku'],$order['agency_id'],$value['goods_number']);
                }
        }
        // 礼包处理
        elseif($value['extension_code']=="libao" && $is_dec){
            if($value['goods_id'] == 0){
                $sql = "UPDATE " . $GLOBALS['ecs']->table('activity_stock') . " SET cart_number = cart_number - $value[goods_number] WHERE parent_id = $value[parent_id] AND area_id = $order[agency_id]";
                $GLOBALS['db']->query($sql);
            }else{
                $sku = ($value['goods_attr_sku']?$value['goods_attr_sku']:$value['goods_sku']);
                $sql = "UPDATE " . $GLOBALS['ecs']->table('goods_stock') . " SET locks_number = locks_number - $value[goods_number] WHERE goods_sku = $sku AND area_id = $order[agency_id]";
                $GLOBALS['db']->query($sql);
            }
        }
        else{
                if ($is_dec)
                {
                    change_goods_storage(($value['goods_attr_sku']?$value['goods_attr_sku']:$value['goods_sku']), $order['agency_id'], - $value['goods_number']);
                }
                else
                {
                    change_goods_storage(($value['goods_attr_sku']?$value['goods_attr_sku']:$value['goods_sku']), $order['agency_id'], $value['goods_number']);
                }
        }
    }
}

/**
 * 商品库存增与减 货品库存增与减
 *
 * @param   int    $good_id         商品ID
 * @param   int    $area_id         服务区ID
 * @param   int    $number          增减数量，默认0；
 * @param   int    $typle           操作类型add为加 out 为减
 * @return  bool               true，成功；false，失败；
 */
function change_goods_storage($goods_sku, $area_id = 3, $number = 0)
{   
    if ($number == 0)
    {
        return true; // 值为0即不做、增减操作，返回true
    }
    if (empty($goods_sku) || empty($number))
    {
        return false;
    }
    if ($number>0) {
        $GLOBALS['virtualStock']->addStock($goods_sku,$number);
        $number = " + " . $number;
        /*增加内存库存*/
    }
    else{
        /*减小内存库存*/
        if (!$GLOBALS['virtualStock']->outStock($goods_sku,abs($number))) {
          return false;
        }
    }


    /* 处理商品库存 */
    $sql = "UPDATE " . $GLOBALS['ecs']->table('goods_stock') . "SET goods_number = goods_number $number WHERE goods_sku = '$goods_sku' AND area_id = $area_id LIMIT 1";
    $query = $GLOBALS['db']->query($sql);

    if ($query)
    {
        return true;
    }
    else
    {
        return false;
    }
}
/**
 * 闪购库存增与减 货品库存增与减
 *
 * @param   int    $good_SKU         商品sku
 * @param   int    $area_id         服务区ID
 * @param   int    $number          增减数量，默认0；
 * @param   int    $limit_id         闪购ID；
 * @return  bool               true，成功；false，失败；
 */
function limit_goods_storage($goods_sku, $area_id = 1, $number = 0 ){
    //检查商品是否在促销中
    $time = time();
    $sql =  " SELECT limit_id FROM ".$GLOBALS['ecs']->table('limit').
            " WHERE goods_sku = $goods_sku AND start_time <= $time AND end_time>= $time AND area_id = $area_id "; 
    $limit_id =  $GLOBALS['db']->getOne($sql);

    if(empty($limit_id)){
         return false;
    }





    if ($number == 0)
    {
        return true; // 值为0即不做、增减操作，返回true
    }
    if (empty($goods_sku) || empty($number))
    {
        return false;
    }
    $buy_num = ($number > 0) ? '+ ' . $number : $number;
    /* 处理闪购库存 */
    $sql = "UPDATE " . $GLOBALS['ecs']->table('limit') . "SET buy_num = buy_num $buy_num ,buy_number = buy_number $buy_num WHERE limit_id = $limit_id LIMIT 1";
    $query = $GLOBALS['db']->query($sql);
    /*查询用户是否有购买改商品记录*/
    $sql =  " SELECT id FROM ". $GLOBALS['ecs']->table('user_limit') .
            " WHERE limit_id = $limit_id AND user_id = ".$_SESSION['user_id']." AND area_id = $area_id";

    $id=$GLOBALS['db']->getOne($sql);

    if($id){
        //更新数据
        $sql = "UPDATE " . $GLOBALS['ecs']->table('user_limit') . " SET buy_num = buy_num  $buy_num WHERE id = $id LIMIT 1";
        $query = $GLOBALS['db']->query($sql);

    }
    else{
        //插入数据
        $sql =  " INSERT INTO " . $GLOBALS['ecs']->table('user_limit') . " (limit_id , user_id,buy_num,area_id) " .
                " VALUES( '$limit_id', '".$_SESSION['user_id']."',$number,$area_id)";
        $query = $GLOBALS['db']->query($sql);

    }



}





/**
 * 取得支付方式id列表
 * @param   bool    $is_cod 是否货到付款
 * @return  array
 */
function payment_id_list($is_cod)
{
    $sql = "SELECT pay_id FROM " . $GLOBALS['ecs']->table('payment');
    if ($is_cod)
    {
        $sql .= " WHERE is_cod = 1";
    }
    else
    {
        $sql .= " WHERE is_cod = 0";
    }

    return $GLOBALS['db']->getCol($sql);
}

/**
 * 生成查询订单的sql
 * @param   string  $type   类型
 * @param   string  $alias  order表的别名（包括.例如 o.）
 * @return  string
 */
function order_query_sql($type = 'finished', $alias = '')
{
    /* 已完成订单 */
    if ($type == 'finished')
    {
        return " AND {$alias}order_status " . db_create_in(array(OS_CONFIRMED, OS_SPLITED)) .
               " AND {$alias}shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) .
               " AND {$alias}pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) . " ";
    }
    /* 待发货订单 */
    elseif ($type == 'await_ship')
    {
        return " AND   {$alias}order_status " .
                 db_create_in(array(OS_CONFIRMED, OS_SPLITED, OS_SPLITING_PART)) .
               " AND   {$alias}shipping_status " .
                 db_create_in(array(SS_UNSHIPPED, SS_PREPARING, SS_SHIPPED_ING)) .
               " AND ( {$alias}pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) . " OR {$alias}pay_id " . db_create_in(payment_id_list(true)) . ") ";
    }
    /* 待付款订单 */
    elseif ($type == 'await_pay')
    {
        return " AND   {$alias}order_status " . db_create_in(array(OS_CONFIRMED, OS_SPLITED)) .
               " AND   {$alias}pay_status = '" . PS_UNPAYED . "'" .
               " AND ( {$alias}shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) . " OR {$alias}pay_id " . db_create_in(payment_id_list(false)) . ") ";
    }
    /* 未确认订单 */
    elseif ($type == 'unconfirmed')
    {
        return " AND {$alias}order_status = '" . OS_UNCONFIRMED . "' ";
    }
    /* 未处理订单：用户可操作 */
    elseif ($type == 'unprocessed')
    {
        return " AND {$alias}order_status " . db_create_in(array(OS_UNCONFIRMED, OS_CONFIRMED)) .
               " AND {$alias}shipping_status = '" . SS_UNSHIPPED . "'" .
               " AND {$alias}pay_status = '" . PS_UNPAYED . "' ";
    }
    /* 未付款未发货订单：管理员可操作 */
    elseif ($type == 'unpay_unship')
    {
        return " AND {$alias}order_status " . db_create_in(array(OS_UNCONFIRMED, OS_CONFIRMED)) .
               " AND {$alias}shipping_status " . db_create_in(array(SS_UNSHIPPED, SS_PREPARING)) .
               " AND {$alias}pay_status = '" . PS_UNPAYED . "' ";
    }
    /* 已发货订单：不论是否付款 */
    elseif ($type == 'shipped')
    {
        return " AND {$alias}order_status = '" . OS_CONFIRMED . "'" .
               " AND {$alias}shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) . " ";
    }
    else
    {
        die('函数 order_query_sql 参数错误');
    }
}

/**
 * 生成查询订单总金额的字段
 * @param   string  $alias  order表的别名（包括.例如 o.）
 * @return  string
 */
function order_amount_field($alias = '')
{
    return "   {$alias}goods_amount + {$alias}tax + {$alias}shipping_fee" .
           " + {$alias}insure_fee + {$alias}pay_fee " ;
}

/**
 * 生成计算应付款金额的字段
 * @param   string  $alias  order表的别名（包括.例如 o.）
 * @return  string
 */
function order_due_field($alias = '')
{
    return order_amount_field($alias) .
            " - {$alias}money_paid - {$alias}surplus - {$alias}integral_money" .
            " - {$alias}bonus - {$alias}discount ";
}

/**
 * 取得购物车该赠送的积分数
 * @return  int     积分数
 */
function get_give_integral()
{
        $sql = "SELECT SUM(c.goods_number * IF(g.give_integral > -1, g.give_integral, c.goods_price))" .
                "FROM " . $GLOBALS['ecs']->table('cart') . " AS c, " .
                          $GLOBALS['ecs']->table('goods') . " AS g " .
                "WHERE c.goods_id = g.goods_id " .
                "AND c.session_id = '" . SESS_ID . "' " .
                "AND c.goods_id > 0 " .
                "AND c.parent_id = 0 " .
                "AND c.rec_type = 0 " .
                "AND c.is_gift = 0";

        return intval($GLOBALS['db']->getOne($sql));
}

/**
 * 取得某订单应该赠送的积分数
 * @param   array   $order  订单
 * @return  int     积分数
 */
function integral_to_give($order)
{
    /* 判断是否团购 */
    if ($order['extension_code'] == 'group_buy')
    {
        include_once(ROOT_PATH . 'includes/lib_goods.php');
        $group_buy = group_buy_info(intval($order['extension_id']));

        return array('custom_points' => $group_buy['gift_integral'], 'rank_points' => $order['goods_amount']);
    }
    else
    {
        $sql = "SELECT SUM(og.goods_number * IF(g.give_integral > -1, g.give_integral, og.goods_price)) AS custom_points, SUM(og.goods_number * IF(g.rank_integral > -1, g.rank_integral, og.goods_price)) AS rank_points " .
                "FROM " . $GLOBALS['ecs']->table('order_goods') . " AS og, " .
                          $GLOBALS['ecs']->table('goods') . " AS g " .
                "WHERE og.goods_id = g.goods_id " .
                "AND og.order_id = '$order[order_id]' " .
                "AND og.goods_id > 0 " .
                "AND og.parent_id = 0 " .
                "AND og.is_gift = 0 AND og.extension_code != 'package_buy'";

        return $GLOBALS['db']->getRow($sql);
    }
}

/**
 * 取得某订单应该赠送的积分数
 * @param   array   $order  订单
 * @return  int     积分数
 */
function integral_to_give_join($order)
{
    /* 判断是否团购 */
    if ($order['extension_code'] == 'group_buy')
    {
        include_once(ROOT_PATH . 'includes/lib_goods.php');
        $group_buy = group_buy_info(intval($order['extension_id']));

        return array('custom_points' => $group_buy['gift_integral'], 'rank_points' => $order['goods_amount']);
    }
    else
    {
        $sql = "SELECT SUM(og.goods_number * IF(g.give_integral > -1, g.give_integral, og.goods_price)) AS custom_points, SUM(og.goods_number * IF(g.rank_integral > -1, g.rank_integral, og.goods_price)) AS rank_points " .
                "FROM " . $GLOBALS['ecs']->table('order_goods') . " AS og, " .
                          $GLOBALS['ecs']->table('goods') . " AS g, " .
                          $GLOBALS['ecs']->table('order_info') . " AS o " .
                "WHERE og.goods_id = g.goods_id " .
                "AND og.order_id = o.order_id " .
                "AND o.join_id = $order[order_sn] " .
                "AND og.goods_id > 0 " .
                "AND og.parent_id = 0 " .
                "AND og.is_gift = 0 AND og.extension_code != 'package_buy'";

        foreach ($GLOBALS['db']->getAll($sql) as $key => $value) {
            $arr['custom_points']+=$value['custom_points'];
            $arr['rank_points']+=$value['rank_points'];
        }
        return $arr;
    }
}



/**
 * 发红包：发货时发红包
 * @param   int     $order_id   订单号
 * @return  bool
 */
function send_order_bonus($order_id)
{
    /* 取得订单应该发放的红包 */
    $bonus_list = order_bonus($order_id);

    /* 如果有红包，统计并发送 */
    if ($bonus_list)
    {
        /* 用户信息 */
        $sql = "SELECT u.user_id, u.user_name, u.email " .
                "FROM " . $GLOBALS['ecs']->table('order_info') . " AS o, " .
                          $GLOBALS['ecs']->table('users') . " AS u " .
                "WHERE o.order_id = '$order_id' " .
                "AND o.user_id = u.user_id ";
        $user = $GLOBALS['db']->getRow($sql);

        /* 统计 */
        $count = 0;
        $money = '';
        foreach ($bonus_list AS $bonus)
        {
            $count += $bonus['number'];
            $money .= $bonus['type_money'] . ' [' . $bonus['number'] . '个], ';

            /* 修改用户红包 */
            $sql = "INSERT INTO " . $GLOBALS['ecs']->table('user_bonus') . " (bonus_type_id, user_id) " .
                    "VALUES('$bonus[type_id]', '$user[user_id]')";
            for ($i = 0; $i < $bonus['number']; $i++)
            {
                if (!$GLOBALS['db']->query($sql))
                {
                    return $GLOBALS['db']->errorMsg();
                }
            }
        }

        /* 如果有红包，发送邮件 */
        if ($count > 0)
        {
            $tpl = get_mail_template('send_bonus');
            $GLOBALS['smarty']->assign('user_name', $user['user_name']);
            $GLOBALS['smarty']->assign('count', $count);
            $GLOBALS['smarty']->assign('money', $money);
            $GLOBALS['smarty']->assign('shop_name', $GLOBALS['_CFG']['shop_name']);
            $GLOBALS['smarty']->assign('send_date', local_date($GLOBALS['_CFG']['date_format']));
            $GLOBALS['smarty']->assign('sent_date', local_date($GLOBALS['_CFG']['date_format']));
            $content = $GLOBALS['smarty']->fetch('str:' . $tpl['template_content']);
            send_mail($user['user_name'], $user['email'], $tpl['template_subject'], $content, $tpl['is_html']);
        }
    }

    return true;
}

/**
 * 返回订单发放的红包
 * @param   int     $order_id   订单id
 */
function return_order_bonus($order_id)
{
    /* 取得订单应该发放的红包 */
    $bonus_list = order_bonus($order_id);

    /* 删除 */
    if ($bonus_list)
    {
        /* 取得订单信息 */
        $order = order_info($order_id);
        $user_id = $order['user_id'];

        foreach ($bonus_list AS $bonus)
        {
            $sql = "DELETE FROM " . $GLOBALS['ecs']->table('user_bonus') .
                    " WHERE bonus_type_id = '$bonus[type_id]' " .
                    "AND user_id = '$user_id' " .
                    "AND order_id = '0' LIMIT " . $bonus['number'];
            $GLOBALS['db']->query($sql);
        }
    }
}

/**
 * 取得订单应该发放的红包
 * @param   int     $order_id   订单id
 * @return  array
 */
function order_bonus($order_id)
{
    /* 查询按商品发的红包 */
    $day    = getdate();
    $today  = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);

    $sql = "SELECT b.type_id, b.type_money, SUM(o.goods_number) AS number " .
            "FROM " . $GLOBALS['ecs']->table('order_goods') . " AS o, " .
                      $GLOBALS['ecs']->table('goods') . " AS g, " .
                      $GLOBALS['ecs']->table('bonus_type') . " AS b " .
            " WHERE o.order_id = '$order_id' " .
            " AND o.is_gift = 0 " .
            " AND o.goods_id = g.goods_id " .
            " AND g.bonus_type_id = b.type_id " .
            " AND b.send_type = '" . SEND_BY_GOODS . "' " .
            " AND b.send_start_date <= '$today' " .
            " AND b.send_end_date >= '$today' " .
            " GROUP BY b.type_id ";
    $list = $GLOBALS['db']->getAll($sql);

    /* 查询定单中非赠品总金额 */
    $amount = order_amount($order_id, false);

    /* 查询订单日期 */
    $sql = "SELECT add_time " .
            " FROM " . $GLOBALS['ecs']->table('order_info') .
            " WHERE order_id = '$order_id' LIMIT 1";
    $order_time = $GLOBALS['db']->getOne($sql);

    /* 查询按订单发的红包 */
    $sql = "SELECT type_id, type_money, IFNULL(FLOOR('$amount' / min_amount), 1) AS number " .
            "FROM " . $GLOBALS['ecs']->table('bonus_type') .
            "WHERE send_type = '" . SEND_BY_ORDER . "' " .
            "AND send_start_date <= '$order_time' " .
            "AND send_end_date >= '$order_time' ";
    $list = array_merge($list, $GLOBALS['db']->getAll($sql));

    return $list;
}

/**
 * 添加礼包到购物车
 *
 * @access  public
 * @param   integer $package_id   礼包编号
 * @param   integer $num          礼包数量
 * @return  boolean
 */
function add_package_to_cart($package_id, $num = 1)
{
    $GLOBALS['err']->clean();

    /* 取得礼包信息 */
    $package = get_package_info($package_id);

    if (empty($package))
    {
        $GLOBALS['err']->add($GLOBALS['_LANG']['goods_not_exists'], ERR_NOT_EXISTS);

        return false;
    }

    /* 是否正在销售 */
    if ($package['is_on_sale'] == 0)
    {
        $GLOBALS['err']->add($GLOBALS['_LANG']['not_on_sale'], ERR_NOT_ON_SALE);

        return false;
    }

    /* 现有库存是否还能凑齐一个礼包 */
    if ($GLOBALS['_CFG']['use_storage'] == '1' && judge_package_stock($package_id))
    {
        $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['shortage'], 1), ERR_OUT_OF_STOCK);

        return false;
    }

    /* 检查库存 */
//    if ($GLOBALS['_CFG']['use_storage'] == 1 && $num > $package['goods_number'])
//    {
//        $num = $goods['goods_number'];
//        $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['shortage'], $num), ERR_OUT_OF_STOCK);
//
//        return false;
//    }

    /* 初始化要插入购物车的基本件数据 */
    $parent = array(
        'user_id'       => $_SESSION['user_id'],
        'session_id'    => SESS_ID,
        'goods_id'      => $package_id,
        'goods_sn'      => '',
        'goods_name'    => addslashes($package['package_name']),
        'market_price'  => $package['market_package'],
        'goods_price'   => $package['package_price'],
        'goods_number'  => $num,
        'goods_attr'    => '',
        'goods_attr_id' => '',
        'is_real'       => $package['is_real'],
        'extension_code'=> 'package_buy',
        'is_gift'       => 0,
        'rec_type'      => CART_GENERAL_GOODS
    );

    /* 如果数量不为0，作为基本件插入 */
    if ($num > 0)
    {
         /* 检查该商品是否已经存在在购物车中 */
        $sql = "SELECT goods_number FROM " .$GLOBALS['ecs']->table('cart').
                " WHERE session_id = '" .SESS_ID. "' AND goods_id = '" . $package_id . "' ".
                " AND parent_id = 0 AND extension_code = 'package_buy' " .
                " AND rec_type = '" . CART_GENERAL_GOODS . "'";

        $row = $GLOBALS['db']->getRow($sql);

        if($row) //如果购物车已经有此物品，则更新
        {
            $num += $row['goods_number'];
            if ($GLOBALS['_CFG']['use_storage'] == 0 || $num > 0)
            {
                $sql = "UPDATE " . $GLOBALS['ecs']->table('cart') . " SET goods_number = '" . $num . "'" .
                       " WHERE session_id = '" .SESS_ID. "' AND goods_id = '$package_id' ".
                       " AND parent_id = 0 AND extension_code = 'package_buy' " .
                       " AND rec_type = '" . CART_GENERAL_GOODS . "'";
                $GLOBALS['db']->query($sql);
            }
            else
            {
                $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['shortage'], $num), ERR_OUT_OF_STOCK);
                return false;
            }
        }
        else //购物车没有此物品，则插入
        {
            $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('cart'), $parent, 'INSERT');
        }
    }

    /* 把赠品删除 */
    $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') . " WHERE session_id = '" . SESS_ID . "' AND is_gift <> 0";
    $GLOBALS['db']->query($sql);

    return true;
}

/**
 * 订单发放奖金
 * $order  发放奖金信息
 * $status 修改状态，默认为1：发放奖金；2：退回奖金；3：修改发放奖金
 */
function order_receive_freeplan($order, $status='1'){
    $ceiling = 1000;
    $sql = "SELECT * FROM ".$GLOBALS['ecs']->table('user_freeplan') ." WHERE user_id = $order[user_id]";
    $freeplan = $GLOBALS['db']->getRow($sql);
    if($freeplan && $order['add_time'] >= $freeplan['addtime']){
        // 发放订单奖金
        if($status == '1'){
            if($freeplan['exam_year'] == '2015年'){
                return false;
            }elseif($freeplan['exam_year'] == '2016年'){
                $ceiling = 2000;
            }else{
                $ceiling = 1000;
            }
            $start_time =strtotime(date('Y-m') . '-01 00:00:00');
            $end_time = strtotime(date('Y') . '-' . ((date('m') < 12) ? (date('m')+1) : 1) . '-01 00:00:00');
            $add_time = time();
            $sql = "SELECT SUM(money) AS sum FROM ".$GLOBALS['ecs']->table('user_freeplan_bonus') ." WHERE user_id = $order[user_id] AND add_time >= $start_time AND add_time < $end_time";
            $freeplan_money = $GLOBALS['db']->getOne($sql);
            $money = $order['goods_amount']+$order['shipping_fee']+$order['freeplan_money'];
            if($freeplan_money >=$ceiling){
                $money = 0;
                return false;
            }else{
                if($money >= $ceiling){
                    $money = $ceiling-$freeplan_money;
                }elseif($money+$freeplan_money>=$ceiling){
                    $money = $ceiling-$freeplan_money;
                }
                if($money <= 0) return false;
                $sql = "INSERT INTO " . $GLOBALS['ecs']->table('user_freeplan_bonus') . "(`user_id`,`money`,`add_time`,`extension_code`, `note`) VALUES('$order[user_id]','$money','$add_time','$order[order_sn]', '发放$order[order_sn]奖金')";
                $GLOBALS['db']->query($sql);
                $sql = "UPDATE " . $GLOBALS['ecs']->table('user_freeplan') . " SET money = money + $money WHERE user_id = $order[user_id]";
                $GLOBALS['db']->query($sql);
                return true;
            }
        }
        // 退回发放的奖金
        elseif($status == '2'){
            $money = $order['goods_amount']+$order['shipping_fee']+$order['freeplan_money'];// 奖金总金额
            //获取之前发放的奖金
            $sql = "SELECT money FROM ".$GLOBALS['ecs']->table('user_freeplan_bonus') ." WHERE user_id = $order[user_id] AND extension_code = '$order[order_sn]' AND money >= 0";
            $freeplan_money = $GLOBALS['db']->getOne($sql);
            if($freeplan_money){
                $add_time = time();
                $sql = "INSERT INTO " . $GLOBALS['ecs']->table('user_freeplan_bonus') . "(`user_id`,`money`,`add_time`,`extension_code`, `note`) VALUES('$order[user_id]','-$money','$add_time','$order[order_sn]', '退回$order[order_sn]奖金')";
                $GLOBALS['db']->query($sql);
                $sql = "UPDATE " . $GLOBALS['ecs']->table('user_freeplan') . " SET money = money - $money WHERE user_id = $order[user_id]";
                $GLOBALS['db']->query($sql);
                return true;
            }else{
                return false;
            }
        }
        // 修改发放奖金
        elseif($status == '3'){
            $money = $order['goods_amount']+$order['shipping_fee']+$order['freeplan_money'];// 奖金总金额
            //获取之前发放的奖金
            $sql = "SELECT money FROM ".$GLOBALS['ecs']->table('user_freeplan_bonus') ." WHERE user_id = $order[user_id] AND extension_code = '$order[order_sn]' AND money > 0";
            $freeplan_money = $GLOBALS['db']->getOne($sql);
            //获取之前退回的奖金
            $sql = "SELECT money FROM ".$GLOBALS['ecs']->table('user_freeplan_bonus') ." WHERE user_id = $order[user_id] AND extension_code = '$order[order_sn]' AND money < 0";
            $back_money = $GLOBALS['db']->getOne($sql);
            $difference = $freeplan_money + $back_money;
            if($difference){// 如果存在差价 修改之前的发放信息
                $sql = "UPDATE " . $GLOBALS['ecs']->table('user_freeplan') . " SET money = money - $difference WHERE user_id = $order[user_id]";
                $GLOBALS['db']->query($sql);
            }
            // 删除有关发放和退回信息
            $sql = "DELETE FROM ". $GLOBALS['ecs']->table('user_freeplan_bonus') . " WHERE user_id = $order[user_id] AND extension_code = '$order[order_sn]'";
            $GLOBALS['db']->query($sql);
            // 重新发放奖金
            order_receive_freeplan($order);
        }
    }
}



/**
 * 得到新发货单号
 * @return  string
 */
function get_delivery_sn()
{
    /* 选择一个随机的方案 */
    mt_srand((double) microtime() * 1000000);

    return date('YmdHi') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}

/**
 * 检查礼包内商品的库存
 * @return  boolen
 */
function judge_package_stock($package_id, $package_num = 1)
{
    $sql = "SELECT goods_id, product_id, goods_number
            FROM " . $GLOBALS['ecs']->table('package_goods') . "
            WHERE package_id = '" . $package_id . "'";
    $row = $GLOBALS['db']->getAll($sql);
    if (empty($row))
    {
        return true;
    }

    /* 分离货品与商品 */
    $goods = array('product_ids' => '', 'goods_ids' => '');
    foreach ($row as $value)
    {
        if ($value['product_id'] > 0)
        {
            $goods['product_ids'] .= ',' . $value['product_id'];
            continue;
        }

        $goods['goods_ids'] .= ',' . $value['goods_id'];
    }

    /* 检查货品库存 */
    if ($goods['product_ids'] != '')
    {
        $sql = "SELECT p.product_id
                FROM " . $GLOBALS['ecs']->table('products') . " AS p, " . $GLOBALS['ecs']->table('package_goods') . " AS pg
                WHERE pg.product_id = p.product_id
                AND pg.package_id = '$package_id'
                AND pg.goods_number * $package_num > p.product_number
                AND p.product_id IN (" . trim($goods['product_ids'], ',') . ")";
        $row = $GLOBALS['db']->getAll($sql);

        if (!empty($row))
        {
            return true;
        }
    }

    /* 检查商品库存 */
    if ($goods['goods_ids'] != '')
    {
        $sql = "SELECT g.goods_id
                FROM " . $GLOBALS['ecs']->table('goods') . "AS g, " . $GLOBALS['ecs']->table('package_goods') . " AS pg
                WHERE pg.goods_id = g.goods_id
                AND pg.goods_number * $package_num > g.goods_number
                AND pg.package_id = '" . $package_id . "'
                AND pg.goods_id IN (" . trim($goods['goods_ids'], ',') . ")";
        $row = $GLOBALS['db']->getAll($sql);

        if (!empty($row))
        {
            return true;
        }
    }

    return false;
}
 ?>